Our Javascript Code
All of these involve number + boolean or number - boolean.
Step-by-Step: Type Coercion in JavaScript
In JavaScript, when you use arithmetic operators like +
and -
, non-number values are converted to numbers if possible.
Boolean to Number Conversion:
true
→ 1false
→ 0💡 Expression 1: 1 + false
Step-by-Step:
false
is converted to0
1 + 0 = 1
Output:
💡 Expression 2: 1 + true
Step-by-Step:
true
is converted to1
1 + 1 = 2
Output:
💡 Expression 3: 1 - false
Step-by-Step:
false
is converted to0
1 - 0 = 1
Output:
🧠 Why Does JavaScript Do This?
Because JavaScript is dynamically typed and loosely typed, it automatically tries to convert values to the most suitable type for the operation.
- When you use
+
or-
, JavaScript assumes you're doing math, so it coerces booleans to numbers.
Summary Table
Expression | Converted Expression | Result |
---|---|---|
1 + false | 1 + 0 | 1 |
1 + true | 1 + 1 | 2 |
1 - false | 1 - 0 | 1 |
✔ Final Answer:
D) 1 2 1
This question appeared in the Deloitte 2nd round of interview, testing the candidate’s knowledge of type coerce of boolean when we use plus (+) and minus (-) operator with number in JavaScript.