AdvancedLesson 26 of 305 min read

Modern syntax: destructuring, spread, rest, ?. and ??

Write shorter, safer code with destructuring, spread and rest, optional chaining and nullish coalescing.

In this lesson you will

  • Destructure objects and arrays
  • Copy and merge with spread
  • Gather arguments with rest
  • Read missing data safely with ?. and ??

About 20 minutes

Say more with less

Modern JavaScript added a handful of small syntax features that, together, change how code feels. Lines that once needed four steps now take one. Once you know them, you will see them in almost every tutorial, library and job. None are hard. Each one solves a specific annoyance you have probably already met.

Destructuring objects

const user = { name: "Sara", age: 28, city: "Lahore", role: "admin" };

// the long way
const name1 = user.name;
const city1 = user.city;

// destructuring
const { name, city } = user;
console.log(name, city);

// rename while pulling out
const { role: job } = user;
console.log(job);                    // admin

// default value if missing
const { country = "Pakistan" } = user;
console.log(country);

// nested
const { address: { zip } = {} } = { address: { zip: "54000" } };
console.log(zip);

The braces on the left of = mirror the shape of the object. Read it as: “from user, take name and city“. It is especially useful for function parameters.

function showUser({ name, age = 18, city = "Unknown" }) {
  return `${name} (${age}) from ${city}`;
}
console.log(showUser({ name: "Ali" }));

Destructuring arrays

const colours = ["red", "green", "blue", "pink"];

const [first, second] = colours;
console.log(first, second);          // red green

const [, , third] = colours;         // skip with empty commas
console.log(third);                  // blue

const [head, ...tail] = colours;     // rest: the remaining items
console.log(head, tail);

// swap two variables without a temp
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b);                   // 2 1

From the settings object, pull out theme and fontSize with a default of 16 for fontSize, and from the array take the first and the rest.

const settings = { theme: 'dark' };
const items = [10, 20, 30, 40];
// destructure and print theme, fontSize, first and rest

const { theme, fontSize = 16 } = settings; const [first, …rest] = items;

const settings = { theme: 'dark' };
const items = [10, 20, 30, 40];
const { theme, fontSize = 16 } = settings;
const [first, ...rest] = items;
console.log(theme, fontSize);
console.log(first, rest);

The spread operator: three dots that unpack

const a = [1, 2, 3];
const b = [4, 5];
console.log([...a, ...b]);               // [1,2,3,4,5]
console.log([0, ...a, 99]);              // add around

const base = { theme: "light", size: 14 };
const custom = { ...base, size: 18, dark: true };
console.log(custom);                      // later keys win

const copy = [...a];                      // shallow copy
console.log(Math.max(...a));              // spread as arguments

Spread builds new arrays and objects rather than changing the old ones. That is exactly what you want when you update state in an app, because the original data stays untouched.

const todo = { id: 1, text: "Learn JS", done: false };
const finished = { ...todo, done: true };       // change one field, keep the rest
console.log(todo.done, finished.done);          // false true
Good to know

Spread makes a shallow copy. Nested objects are still shared between the copy and the original. For a full deep copy use structuredClone(obj).

The rest parameter: three dots that gather

function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4));        // 10

function log(level, ...messages) {
  console.log(`[${level}]`, messages.join(" "));
}
log("INFO", "Server", "started");

The same three dots mean opposite things depending on the side: in a call or literal they spread out; in a definition or pattern they gather up.

Optional chaining ?.

const user = { profile: { address: null } };

// console.log(user.profile.address.city);   // TypeError!
console.log(user.profile.address?.city);     // undefined, no crash
console.log(user.settings?.theme);           // undefined
console.log(user.getName?.());               // call only if it exists
const list = null;
console.log(list?.[0]);                      // safe index

Nullish coalescing ?? and logical assignment

const count = 0;
console.log(count || 10);      // 10: || treats 0 as missing (oops)
console.log(count ?? 10);      // 0 : ?? only replaces null and undefined

const input = "";
console.log(input ?? "default");   // "" kept
console.log(input || "default");   // "default"

let settings = { volume: 0 };
settings.volume ??= 50;       // assign only if null/undefined -> stays 0
settings.theme ??= "light";   // missing -> assigned
settings.retries ||= 3;       // assign if falsy
console.log(settings);

Use ?? when zero, false or an empty string are legitimate values. Use || when any “falsy” value should be replaced. Together, ?. and ?? let you read messy data safely: data?.user?.name ?? "Guest".

Safely read the city from each user, showing ‘Unknown’ when missing, and the number of orders, keeping 0 as 0.

const users = [
  { name: 'Sara', address: { city: 'Lahore' }, orders: 0 },
  { name: 'Ali', orders: 3 },
  { name: 'Mina', address: null }
];
for (const u of users) {
  // print name, city or Unknown, orders ?? 'n/a'
}

console.log(u.name, u.address?.city ?? ‘Unknown’, u.orders ?? ‘n/a’);

const users = [
  { name: 'Sara', address: { city: 'Lahore' }, orders: 0 },
  { name: 'Ali', orders: 3 },
  { name: 'Mina', address: null }
];
for (const u of users) {
  console.log(u.name, u.address?.city ?? 'Unknown', u.orders ?? 'n/a');
}

Handy modern helpers

Feature Example
Short property names { name, age } instead of { name: name, age: age }
Computed keys { [field]: value }
Object.entries and fromEntries Loop an object or build one from pairs
Array.at(-1) Last item
flat() and flatMap() Flatten nested arrays
structuredClone() Deep copy
Set and Map Unique values, and key-value pairs with any key type
Numeric separators 1_000_000 for readability
const prices = { pen: 20, bag: 900, ruler: 60 };

const doubled = Object.fromEntries(
  Object.entries(prices).map(([item, price]) => [item, price * 2])
);
console.log(doubled);

const unique = [...new Set([3, 1, 3, 2, 1])];
console.log(unique);                      // [3,1,2]

const nested = [[1, 2], [3, [4]]];
console.log(nested.flat(2));              // [1,2,3,4]

Use Object.entries with map and fromEntries to apply a 10 percent discount to every price in the object.

const prices = { pen: 20, bag: 900, ruler: 60 };
// build discounted prices

Object.fromEntries(Object.entries(prices).map(([k, v]) => [k, v * 0.9]))

const prices = { pen: 20, bag: 900, ruler: 60 };
const sale = Object.fromEntries(
  Object.entries(prices).map(([item, price]) => [item, price * 0.9])
);
console.log(sale);
Common mistake

Using || for defaults on values that can legitimately be 0 or an empty string, such as volume || 50, which turns a deliberate 0 into 50. Use ?? instead.

Read code aloud

const { a, ...others } = obj reads as: “take a out of obj, and gather the remaining properties into others“. Saying it in words is the fastest way to master this syntax.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does const { name } = user do?

  1. Deletes name
  2. Creates a class
  3. Copies the user
  4. Creates a variable name from user.name

Destructuring pulls out a property.

What does [...a, ...b] produce?

  1. A new array combining a and b
  2. A string
  3. Changes a
  4. An error

Spread unpacks both into a new array.

What is 0 ?? 10?

  1. 10
  2. null
  3. 0
  4. undefined

?? only replaces null or undefined.

What does user?.address?.city return if address is undefined?

  1. An error
  2. null
  3. “”
  4. undefined

Optional chaining stops safely.

In function f(...args), what are the three dots?

  1. Spread
  2. Rest: gathers arguments into an array
  3. A comment
  4. A range

In a definition they gather.

Summary

  • Destructuring pulls values out by shape.
  • Spread copies and merges; rest gathers.
  • ?. avoids crashes on missing data.
  • ?? keeps 0 and empty text as valid values.

Next lesson

Next: regular expressions, a mini language for searching and checking text.

Questions

Is spread the same as a deep copy?

No. It is shallow. Use structuredClone for deep copies.

When do I use ?? and when //?

Use ?? when 0, false or empty text are valid values; use || to replace any falsy value.

Does optional chaining work with functions?

Yes: obj.method?.() calls it only if it exists.

Progress is saved in this browser.