All sample questions / JavaScript

What does console.log(JSON.stringify(rest)) print? JavaScript Arrays and Iteration

Block 4, Arrays and Iteration, question 12 of the JavaScript sample

const [first, ...rest] = [1, 2, 3, 4];
console.log(JSON.stringify(rest));

What does this print?

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

Answer, A. [2,3,4]

A. [2,3,4]
Correct. first takes the initial element, 1, and the rest pattern collects everything that remains afterward into a new array, 2, 3 and 4.
B. [1,2,3,4]
Assumes the rest pattern collects the entire original array alongside the named binding. The rest pattern only collects whatever elements are left over after the earlier named bindings have taken their share.
C. [3,4]
Drops one extra element from the front, as if two positions were named instead of one. Only first is named here, so rest correctly starts collecting from the second element onward.
D. [1]
Swaps the roles, as if the rest pattern captured only what first took. first binds to a single value taken from the front, while rest always collects everything that remains after it.

A rest element in a destructuring pattern must come last, and it gathers every remaining value that was not already claimed by an earlier named binding into a genuine new array. This mirrors rest parameters in function definitions, which collect any extra arguments beyond the named ones.

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.