Our Javascript Code Expression
❓ What’s Happening Here?
We’re subtracting a number from a string.
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"→ string5→ 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
✔ 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:
➖ The -, *, /, % Operators
- These are pure arithmetic.
- JavaScript will always try to convert both operands to numbers before the operation.
🧪 Bonus Examples
Remember Key Takeaways
| Operator | Behavior 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?
