codecks.

Arrays & objects · Output question

JavaScript default sort after copying an array

An array of numbers is copied and sorted without a comparator. Predict both the sorted result and the original order.

const sizes = [9, 12, 4];
const ordered = [...sizes].sort();
console.log(sizes.join(","));
console.log(ordered.join(","));

What gets logged?

Choose an output before opening the walkthrough, or check your answer in practice mode.

  1. 9,12,4
    4,9,12
  2. 9,12,4
    12,4,9
  3. 12,4,9
    12,4,9
  4. 4,9,12
    4,9,12
Reveal the answer and execution trace
9,12,4
12,4,9

sort compares string values by default. The spread protects the original array from the in-place sort.

  1. Line 2. Spreading sizes produces a different array containing the same numbers.
  2. Line 2. Default sort compares "12", "4", and "9" as strings, in that order.
  3. Line 3. sizes still holds 9, 12, and 4 in its original order.
  4. Line 4. ordered contains 12, 4, and 9.

Reference: Array sort on MDN.