JavaScript Trick Question: Adding and Subtracting Booleans with Numbers – Deloitte Interview Example


Our Javascript Code

console.log(1 + false); // ?
console.log(1 + true); // ? console.log(1 - false); // ?

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   →    1
false  →    0

💡 Expression 1: 1 + false

Step-by-Step:

  1. false is converted to 0
  2. 1 + 0 = 1

Output:

1

💡 Expression 2: 1 + true

Step-by-Step:

  1. true is converted to 1
  2. 1 + 1 = 2

Output:

2

💡 Expression 3: 1 - false

Step-by-Step:

  1. false is converted to 0
  2. 1 - 0 = 1

Output:

1

🧠 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.

Post a Comment

Previous Post Next Post