What Happens When You Subtract a Number from a String in JavaScript? – Tech Mahindra Interview Question.


Our Javascript Code Expression

console.log("5" - 5);

❓ What’s Happening Here?

We’re subtracting a number from a string.

"5" - 5

JavaScript sees that you’re using the - operator. which is strictly arithmetic, not string concatenation so it automatically tries to convert both operands to numbers.


Step-by-Step Breakdown

🔸 Step 1: Identify the types

  • "5" → string
  • 5 → number

🔸 Step 2: Apply Type Coercion

  • When using the - operator, JavaScript will convert "5" to a number before subtraction.
  • "5"5 (string to number)

🔸 Step 3: Subtract

5 - 5 = 0

✔ Final Answer:

B) 0

This question appeared in the Tech Mahindra 2nd round of interview, testing the candidate’s knowledge of type coercion of number and string when using minus (-) operator in JavaScript.


🧠 Why Didn’t It Concatenate?

Great question! That’s because JavaScript behaves differently depending on the operator:

➕ The + Operator

  • If one operand is a string, JavaScript concatenates.
  • Example:

        console.log("5" + 5); // "55"

➖ The -, *, /, % Operators

  • These are pure arithmetic.
  • JavaScript will always try to convert both operands to numbers before the operation.


🧪 Bonus Examples

console.log("10" - "3"); // 7
console.log("10" * "2"); // 20 console.log("10" / "2"); // 5 console.log("10" - true); // 9 (true → 1) console.log("10" - false); // 10 (false → 0)

Remember Key Takeaways

OperatorBehavior with Strings
    +        Concatenates if either operand is a string
  - * /        Converts to numbers and performs math

JavaScript is flexible, but sometimes sneaky! If you're ever unsure, just ask: “Is this operator for math or for strings?” That usually clears it up. Want to try some tricky ones with null, undefined, or arrays next? 

Post a Comment

Previous Post Next Post