This is a classic example of type coercion in JavaScript, especially when working with different data types in an arithmetic operation.
Here’s your code:
let x = "5";let y = true; console.log(x - y);
Let’s break it down step-by-step like a pro teacher:
Step 1: Variable Declarations :-
let x = "5";
xis a string, holding the text"5", not the number 5.
let y = true;
yis a boolean, holding the valuetrue.
Step 2: The Expression — x - y :-
Now we evaluate:
"5" - true
🔸 What Happens Behind the Scenes?
In JavaScript, the - operator only works on numbers, so JavaScript automatically converts both operands into numbers using type coercion:
"5" → Number- A string
"5" is coerced to the number 5.
true → Number- The boolean
true is coerced to 1 (and false would be 0).
"5" → Number- A string
"5"is coerced to the number5.
true → Number- The boolean
trueis coerced to1(andfalsewould be0).
👉 So this becomes:
5 - 1
Step 3: The Result :-
5 - 1 = 4
So the final output is:
console.log(4); // → 4✔ Final Answer:
A) 4
This question appeared in the TCS 2nd round of interview, testing the candidate’s knowledge of type coercion between numeric string and number when we negate them in JavaScript.
