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".
const utente = { nome: 'Anna', eta: 28, ruolo: 'admin' };
const { nome, eta } = utente;
console.log(nome); // 'Anna'
console.log(eta); // 28Renaming
Add : newName after the key:
const { nome: n, eta: years } = utente;
// creates the variables n and yearsDefault value
If the property is missing (or is undefined), the default is used:
const { ruolo = 'reader', telefono = 'n/d' } = utente;
// ruolo = 'admin' (present), telefono = 'n/d' (missing)Array destructuring
It works by position:
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:
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:
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
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').
Show hint
const { name, city } = user; then a template literal with the two values.
Solution available after 3 attempts
Review exercise
Given `base = { theme: 'dark', size: 'md' }`, return a NEW identical object but with `size` set to 'lg' using spread.
Show hint
The last expression must be the object. Wrap it in parentheses: ({ ...base, ... }).
Solution available after 3 attempts