All sample questions / JavaScript

JavaScript Objects, Destructuring and Immutability, what does console.log(firstItem) print after const { list: [firstItem] } = { list: ['a', 'b'] }?

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

const { list: [firstItem] } = { list: ['a', 'b'] };
console.log(firstItem);

What does this print?

  1. A. a
  2. B. ["a","b"]
  3. C. undefined
  4. D. b
Show the answer and why each option is right or wrong

Answer, A. a

A. a
Correct. The nested array pattern takes the first element of list, which is the string a.
B. ["a","b"]
Assumes list, once renamed inside the pattern, ends up holding the whole array instead of just its first element.
C. undefined
Assumes mixing object and array destructuring in a single pattern is not supported.
D. b
Assumes an array pattern nested inside an object pattern takes the last element rather than the first.

Object and array destructuring patterns can be nested inside each other freely. An array pattern used as the value of an object property destructures the array found at that property using ordinary positional rules, starting from index 0.

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.