JavaScript Destructuring, Spread, and Rest with React Examples

Learn JavaScript array and object destructuring, spread for copying and React state updates, and rest for collecting remaining values.

JavaScript Destructuring, Spread, and Rest with React Examples

JavaScript Destructuring, Spread, and Rest

These features use a little syntax to make common JavaScript work easier. Destructuring reads values out of arrays or objects into variables. Spread expands an iterable or object into another place. Rest collects remaining values into a new array or object. Spread and rest use the same ... syntax; context tells you which job it is doing.

Destructuring arrays

Array destructuring assigns items by position:

const colors = ["teal", "orange", "purple"];
const [firstColor, secondColor] = colors;

console.log(firstColor); // "teal"
console.log(secondColor); // "orange"

You can skip a position with an extra comma, set a default, or collect the remaining items with rest:

const [first, , third, fourth = "gray"] = ["red", "blue", "green"];
console.log(first, third, fourth); // "red" "green" "gray"

const [head, ...otherColors] = ["red", "blue", "green"];
console.log(otherColors); // ["blue", "green"]

Destructuring objects

Object destructuring reads properties by name, so the variable names normally match the property names:

const article = {
  title: "Getting Started with JavaScript",
  image: "/images/javascript.png",
};

const { title, image } = article;
console.log(title); // "Getting Started with JavaScript"

You can rename a variable with propertyName: newName and provide a default for a missing or undefined property:

const { title: articleTitle, author = "Guest" } = article;
console.log(articleTitle); // "Getting Started with JavaScript"
console.log(author); // "Guest"

The default applies when the property is undefined, not when it is null.

Destructure React props

React passes a component's props as an object. Destructuring in the function parameter gives the component direct names for the values it uses:

function ArticleCard({ title, image }) {
  return (
    <article>
      <img src={image} alt="" />
      <h2>{title}</h2>
    </article>
  );
}

This is equivalent in idea to accepting props and reading props.title and props.image, but it avoids repeating props.. This is ordinary JavaScript object destructuring in a React component.

Spread: expand or copy values

Spread expands array elements into a new array. This is useful when you want a copy with an item added or removed without changing the original array:

const original = ["HTML", "CSS"];
const withJavaScript = [...original, "JavaScript"];

console.log(withJavaScript); // ["HTML", "CSS", "JavaScript"]
console.log(original); // ["HTML", "CSS"]

For objects, spread copies enumerable own properties into a new object. Later properties override earlier properties with the same key:

const defaults = { theme: "light", compact: false };
const preferences = { ...defaults, theme: "dark" };

console.log(preferences); // { theme: "dark", compact: false }

Updating React state immutably

When React state is an object, create a new object when updating it instead of changing the existing object in place. React compares state values when deciding whether an update is new; setting the same mutated object reference can be ignored. A new object makes the update explicit:

import { useState } from "react";

function ProfileEditor() {
  const [profile, setProfile] = useState({ name: "Likhon", theme: "light" });

  function chooseDarkTheme() {
    setProfile((currentProfile) => ({
      ...currentProfile,
      theme: "dark",
    }));
  }

  return <button onClick={chooseDarkTheme}>Use dark theme</button>;
}

The updater receives the latest state, spreads its properties into a new object, and replaces theme. The original state object was not edited.

Spread makes a shallow copy. If an object contains nested objects or arrays, those nested values are still shared references. Copy each level you need to change:

const nextProfile = {
  ...profile,
  settings: {
    ...profile.settings,
    theme: "dark",
  },
};

Rest: collect what remains

In destructuring, rest collects unassigned items or properties. In a function parameter, it collects any remaining arguments into an array:

function total(...numbers) {
  return numbers.reduce((sum, number) => sum + number, 0);
}

console.log(total(4, 7, 9)); // 20

In object destructuring, rest collects the remaining properties into a new object:

const { title: cardTitle, ...otherDetails } = {
  title: "JavaScript",
  level: "Beginner",
  duration: 12,
};

console.log(cardTitle); // "JavaScript"
console.log(otherDetails); // { level: "Beginner", duration: 12 }

The rest element must be last in its destructuring pattern or parameter list. In function parameters, only one rest parameter is allowed, and it must be last.

Spread vs. rest

Syntax useWhat it doesExample
SpreadExpands values out[...items, newItem]
RestCollects remaining values infunction logAll(...values) {}

Try it yourself

Given the product below, destructure name and price. Use spread to create a new object with a discounted price, while keeping the original unchanged. Then use rest to collect any extra arguments in a function.

const product = { name: "Keyboard", price: 80, category: "accessories" };

Recap

  • Destructuring reads array items by position and object properties by name.
  • Spread expands values into a new array or object; it is useful for immutable updates.
  • Rest gathers remaining values into an array or object.
  • Object and array spread make shallow copies, so nested values need care.

What's next?

Next, we’ll look more closely at why immutability matters in React.

Written by

Dev Likhon

Dev Likhon

Full Stack Developer & Tech Educator

6+ years of professional development experience.

About Me
Share:

Comments

Share what you learned or ask a question.

Loading comments...