Skip to main content
eLearner.app
Module 3 · Lesson 3 of 411/32 in the course~12 min
Module lessons (3/4)

Destructuring and spread

Two sibling syntaxes from the same family, introduced by ES6 and now daily bread for anyone writing modern JS:

  • Destructuring: extract multiple values from arrays/objects in a single line.
  • Spread ...: "spreads" an array or an object inside another.

Together they make code far more concise and readable.

Object destructuring

Read out loud: "create the constants nome and eta with the values of the same-named properties of utente".

JS
const utente = { nome: 'Anna', eta: 28, ruolo: 'admin' };

const { nome, eta } = utente;
console.log(nome); // 'Anna'
console.log(eta); // 28

Renaming

Add : newName after the key:

JS
const { nome: n, eta: years } = utente;
// creates the variables n and years

Default value

If the property is missing (or is undefined), the default is used:

JS
const { ruolo = 'reader', telefono = 'n/d' } = utente;
// ruolo = 'admin' (present), telefono = 'n/d' (missing)

Array destructuring

It works by position:

JS
const colori = ['rosso', 'verde', 'blu'];
const [primo, secondo] = colori;
// primo = 'rosso', secondo = 'verde'

const [, , terzo] = colori; // skips the first two
const [a, ...resto] = colori; // a = 'rosso', resto = ['verde','blu']

Spread on arrays

...arr "spreads" the elements:

JS
const a = [1, 2, 3];
const b = [4, 5];

const unione = [...a, ...b]; // [1, 2, 3, 4, 5]
const copia = [...a]; // shallow copy of a
const conPiu = [0, ...a, 4]; // [0, 1, 2, 3, 4]

Spread on objects

Later keys override earlier ones — fundamental for immutable updates:

JS
const utente = { nome: 'Anna', eta: 28 };

const aggiornato = { ...utente, eta: 29 };
// { nome: 'Anna', eta: 29 } — utente was NOT touched

const con = { ...utente, attivo: true };
// { nome: 'Anna', eta: 28, attivo: true }

Try it

Exercise#js.m3.l3.e1
Attempts: 0Loading…

Given `user = { name: 'Marco', age: 34, city: 'Torino' }`, use destructuring to extract just `name` and `city` into two constants and return `\`${name} di ${city}\`` (must equal 'Marco di Torino').

Loading editor…
Show hint

const { name, city } = user; then a template literal with the two values.

Solution available after 3 attempts

Review exercise

Exercise#js.m3.l3.e2
Attempts: 0Loading…

Given `base = { theme: 'dark', size: 'md' }`, return a NEW identical object but with `size` set to 'lg' using spread.

Loading editor…
Show hint

The last expression must be the object. Wrap it in parentheses: ({ ...base, ... }).

Solution available after 3 attempts