nameagenameage012firstnameage0101231const user = { name: "Ada", age: 36 };2const { name, age } = user;3const nums = [10, 20, 30];4const [first, ...rest] = nums;5const more = [...nums, 40];6const older = { ...user, age: 37 };"Ada"3610203010203040"Ada"3637
Back: memory. Objects (property names), arrays (indexes 0, 1, 2 ...) and plain variablesFront: the program, data.js, six linesTokens: new objects and arrays, and the values copied out of them and into themAt the back, a memory board with every box the program makes: objects show property names, arrays show indexes 0, 1, 2, and plain variables show their own name. Faint boxes do not exist yet. Lines 2 and 4 destructure: values hop out of user and nums into new variables. Lines 5 and 6 spread: values are copied into a new array and a new object. Spread makes a shallow copy: it copies each top-level value. If a value is itself an object or array, the new one refers to the same inner object, so changing that inner object shows up in both.

Out and in

  1. Destructuring unpacks values out of an object or an array into separate variables, in one line. Spread, written ..., does the opposite: it copies all the items into a new array or object.

Unpacking

Spreading

What happens

// step 1/8 · idea
destructuring   take values OUT into variables
                const { a, b } = obj;   by name
                const [x, y] = arr;     by position
spread  ...     copy values INTO a new one
                [...arr]   { ...obj }
standard        ECMAScript 2015 (2018 for objects ...)

Spread makes a shallow copy: it copies each top-level value. If a value is itself an object or array, the new one refers to the same inner object, so changing that inner object shows up in both. The figure draws each variable as its own box holding a copy of the value. For numbers and text that is exactly what happens; for objects and arrays a variable holds a reference to the one object.