All sample questions / JavaScript

What does console.log(1 + 2 + 'a') print? JavaScript Types, Coercion and Equality

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

console.log(1 + 2 + 'a');

What does this print?

  1. A. NaNa
  2. B. 12a
  3. C. a3
  4. D. 3a
Show the answer and why each option is right or wrong

Answer, D. 3a

A. NaNa
Assumes the string appearing later in the expression corrupts the earlier numeric addition into an invalid number.
B. 12a
Assumes every operand becomes a string from the start because a string appears somewhere in the expression, instead of evaluating left to right until a string is introduced.
C. a3
Assumes the string operand is joined first and the numbers are appended after it.
D. 3a
Correct. The two numbers add normally first since no string has appeared yet, and the string only joins in at the last step.

Left to right evaluation means 1 + 2 completes as ordinary numeric addition before the string ever enters the picture. Only the final plus, the one touching the string, switches to concatenation.

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.