All sample questions / JavaScript
What does console.log(handle(new TimeoutError('late'))) print? JavaScript Errors, Control Flow and Sharp Edges
Block 8, Errors, Control Flow and Sharp Edges, question 7 of the JavaScript sample
class NotFoundError extends Error {}
class TimeoutError extends Error {}
function handle(err) {
if (err instanceof NotFoundError) return 'missing';
if (err instanceof TimeoutError) return 'slow';
return 'unknown';
}
console.log(handle(new TimeoutError('late')));
What does this print?
Show the answer and why each option is right or wrong
Answer, B. slow
- A. TimeoutError
- Confuses the return value with the constructor name of the error object passed in.
- B. slow
- Correct. instanceof checks the exact prototype chain of the passed object, and only the TimeoutError branch matches it.
- C. unknown
- Assumes instanceof only matches the base Error class and not user defined subclasses, but a class extending Error still satisfies instanceof for itself.
- D. missing
- Assumes both custom classes are indistinguishable subclasses of Error and the first branch always wins, but instanceof checks the specific prototype chain of the object being tested.
instanceof walks the prototype chain of the object and checks each link against the given constructor. A TimeoutError instance is only an instance of TimeoutError and Error, never of an unrelated sibling class.
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.