All sample questions / JavaScript

What does console.log(e + 8) print? JavaScript Errors, Control Flow and Sharp Edges

Block 8, Errors, Control Flow and Sharp Edges, question 17 of the JavaScript sample

try {
  throw 42;
} catch (e) {
  console.log(e + 8);
}

What does this print?

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

Answer, A. 50

A. 50
Correct. The caught value is the plain number 42, and adding 8 to it gives an ordinary numeric result.
B. 42
Assumes the addition never runs because the caught value is not an Error instance, but any thrown value reaches the catch block and can be used normally.
C. NaN
Assumes a thrown non Error value cannot be combined with a number and coerces into something unusable, but a thrown number behaves exactly like any other number.
D. undefined8
Assumes the caught value is undefined because the thrown target was not an Error object, then concatenates it with the second operand as a string.

Throwing a primitive value like a number delivers that exact value to catch. Arithmetic on it proceeds normally, there is no requirement that a thrown value be an Error for it to be usable afterward.

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.