JavaScript Type Coercion Explained. What Happens When You Add Boolean and Number or String. Data Type Magic in JavaScript. Boolean Numbers and Strings Interaction Explained

JavaScript Type Coercion Explained. What Happens When You Add Boolean and Number or String. Data Type Magic in JavaScript. Boolean Numbers and Strings Interaction Explained

Lets explain the Code:

console.log(true + 1);
console.log(true + "1");

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 becomes 1
  • false becomes 0

Calculation:

true + 11 + 12

Console Output:

2

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:

true + "1""true" + "1""true1"

Console Output:

true1

JavaScript Type Coercion Summary:

ExpressionCoercion TypeResult
true + 1Number2
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:

  1. If either operand is a string → string concatenation happens.
  2. If both operands are numbers (or coerced to numbers) → numeric addition happens.


Quick Real-World Example:

console.log(false + 5); // Output: 5 → false is treated as 0
console.log(false + "5"); // Output: "false5" → string concatenation

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.

Post a Comment

Previous Post Next Post