Lets explain the Code:
Step 1: console.log(true + 1);
What is Happening:
Here, you are adding a boolean value true
to a number 1
.
JavaScript Type Coercion (Automatic Type Conversion):
When using the +
operator, JavaScript automatically converts operands to compatible types based on the context.
When adding:
- Boolean + Number → Boolean is coerced to a number.
Coercion Rule:
true
becomes1
false
becomes0
Calculation:
Console Output:
Step 2: console.log(true + "1");
What is Happening:
Here, you are adding a boolean value true
to a string "1"
.
JavaScript Type Coercion:
When using the +
operator:
- If any operand is a string, JavaScript performs string concatenation.
Coercion Rule:
true
is converted to the string"true"
Calculation:
Console Output:
JavaScript Type Coercion Summary:
Expression | Coercion Type | Result |
---|---|---|
true + 1 | Number | 2 |
true + "1" | String | "true1" |
Why This Happens:
- In
true + 1
: Both operands are treated as numbers → arithmetic addition. - In
true + "1"
: One operand is a string → string concatenation happens.
Type Conversion Rules:
- If either operand is a string → string concatenation happens.
- If both operands are numbers (or coerced to numbers) → numeric addition happens.
Quick Real-World Example:
Final Key Takeaways:
- JavaScript automatically converts types based on the operator and the types of operands.
+
is the only operator that behaves differently: it can mean addition or string concatenation.- Boolean values:
- true → 1
- false → 0
- When a string is involved, everything is converted to a string.
✔ Final Answer:
B) 2 true1
This question appeared in the HCL Tech 2nd round of interview, testing the candidate’s knowledge of type coercion when use + operator between boolean, string and number in JavaScript.