All sample questions / JavaScript

JavaScript Objects, Destructuring and Immutability, what does console.log(id) print after const response = { data: { user: { id: 7 } } }?

Block 5, Objects, Destructuring and Immutability, question 9 of the JavaScript sample

const response = { data: { user: { id: 7 } } };
const { data: { user: { id } } } = response;
console.log(id);

What does this print?

  1. A. ReferenceError
  2. B. {"id":7}
  3. C. 7
  4. D. undefined
Show the answer and why each option is right or wrong

Answer, C. 7

A. ReferenceError
Assumes id is never declared because the pattern only introduces bindings for data and user.
B. {"id":7}
Assumes the innermost pattern binds the whole user object rather than just its id property.
C. 7
Correct. Nested destructuring walks down through data and user and binds id to the number stored three levels deep.
D. undefined
Assumes destructuring through several nested levels in one pattern is not valid and silently produces undefined.

Object destructuring can nest arbitrarily deep, each colon steps into a property of the previous level. Only the innermost names actually become variables, the intermediate names like data and user are just path segments.

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.