All sample questions / JavaScript

What does console.log('5' - 2) print? JavaScript Types, Coercion and Equality

Block 1, Types, Coercion and Equality, question 4 of the JavaScript sample

console.log('5' - 2);

What does this print?

  1. A. 7
  2. B. 3
  3. C. 52
  4. D. NaN
Show the answer and why each option is right or wrong

Answer, B. 3

A. 7
Adds the two values together instead of subtracting them.
B. 3
Correct. Minus has no concatenation meaning, so it always converts both operands to numbers before subtracting.
C. 52
Assumes the minus operator concatenates strings the same way the plus operator can.
D. NaN
Assumes subtraction cannot coerce a numeric string into a number the way addition would.

Unlike plus, minus never means concatenation. It coerces both sides to numbers unconditionally, so a numeric string behaves exactly like the number it represents.

The answer above is what the Node interpreter printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 600 JavaScript interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 600 JavaScript questions, 9 euros

Or play the free JavaScript sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.