JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 9: Modern JavaScript SyntaxLesson 42 of 150About 40 minutes

Lesson 42: Spread and rest syntax

01Opening question

You want a copy of a cart with one more item, without changing the original. How do you spread the old items into a new list?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

The three dots spread values out of an array or object into a new one.

const cart = ["apple", "bread"];
const bigger = [...cart, "milk"];
console.log(cart, bigger);
const user = { name: "Ada", plan: "free" };
console.log({ ...user, plan: "pro" });

03Objective and prerequisites

Learning objective: Use spread syntax to copy and combine arrays and objects, pass array elements as arguments, and collect remaining values with rest syntax.

You need: Lesson 39: Object copying and reference behavior, Lesson 41: Destructuring

Skills practised: Spread and rest syntax.

04Explanation

Spread (...) expands an array's items or an object's properties into a new array, object or argument list: [...a, ...b] joins two arrays.

Spread makes a new array or object, so changing the copy does not change the original's top level.

In objects, later properties win: { ...user, plan: "pro" } copies user and then replaces plan.

Rest uses the same dots on the receiving side to collect what is left: function sum(...numbers) gathers all arguments into an array, and const [first, ...others] = list; collects the remaining items.

05Definitions

Spread syntax
... used to expand an array or object into individual elements or properties.
Rest parameter
...name in a parameter list, collecting remaining arguments into an array.
Rest element
...name in a destructuring pattern, collecting the remaining items or properties.
Shallow copy
A new top-level array or object whose nested values are still shared with the original.

Open the full glossary

06Visual learning object

Spread and rest explorer. Step through spreading arrays and objects and collecting the rest, and see which values are new and which are shared.

Loading the interactive object…

Open the full Spread and rest explorer page with its guided experiment.

07Examples

ex-042-01Combine arrays Browser-executable JavaScript

Spread places each item of each array into the new array.

const fruit = ["apple", "pear"];
const veg = ["leek"];
const basket = [...fruit, ...veg, "bread"];
console.log(basket);
console.log(fruit.length, basket.length);
Sample input
None
Expected output
["apple", "pear", "leek", "bread"] 2 4
Common mistake
Writing [fruit, veg], which nests the arrays instead of combining them.
Try this
Put bread at the start instead.
Source
examples/ex-042-01-combine-arrays.js (repository pending publication)

ex-042-02Copy and update an object Browser-executable JavaScript

Later properties override earlier ones.

const account = { name: "Grace", plan: "free", seats: 1 };
const upgraded = { ...account, plan: "team", seats: 5 };
console.log(account);
console.log(upgraded);
Sample input
None
Expected output
{name: "Grace", plan: "free", seats: 1} {name: "Grace", plan: "team", seats: 5}
Common mistake
Putting ...account last, which overwrites the new values with the old ones.
Try this
Swap the order and predict the result.
Source
examples/ex-042-02-update-object.js (repository pending publication)

ex-042-03Rest parameters Browser-executable JavaScript

Rest collects any number of arguments into a real array.

function total(label, ...amounts) {
  const sum = amounts.reduce((a, b) => a + b, 0);
  return `${label}: ${sum} (${amounts.length} items)`;
}
console.log(total("Lunch", 4, 6, 2));
console.log(total("Nothing"));
Sample input
None
Expected output
Lunch: 12 (3 items) Nothing: 0 (0 items)
Common mistake
Putting the rest parameter first; it must be last.
Try this
Add an average to the label.
Source
examples/ex-042-03-rest-parameter.js (repository pending publication)

ex-042-04Omit fields with object rest Browser-executable JavaScript

Destructure the fields to drop and keep the rest.

const user = { id: 3, name: "Linus", password: "hunter2", email: "linus@example.com" };
const { password, ...publicUser } = user;
console.log(publicUser);
Sample input
None
Expected output
{id: 3, name: "Linus", email: "linus@example.com"}
Common mistake
Deleting the property from the original object, which mutates data other code may need.
Try this
Also omit email.
Source
examples/ex-042-04-omit-fields.js (repository pending publication)

ex-042-05Spread is shallow Browser-executable JavaScript

Nested objects are shared between the original and the copy.

const original = { name: "Plan A", tags: ["new"] };
const copy = { ...original };
copy.name = "Plan B";
copy.tags.push("edited");
console.log(original);
Sample input
None
Expected output
{name: "Plan A", tags: ["new", "edited"]}
Common mistake
Assuming spread makes a deep copy.
Try this
Fix it by also spreading tags: { ...original, tags: [...original.tags] }.
Source
examples/ex-042-05-shallow.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the nested array

Combine arrays instead of nesting them.

const morning = ["email", "standup"];
const afternoon = ["review"];
const day = [morning, afternoon];
console.log(day.length);

Toggle a setting immutably

Create an updated copy instead of mutating.

const settings = { theme: "light", alerts: true };
// TODO: create next as a copy of settings with theme "dark"
console.log(settings.theme, next.theme);

Merge tag lists

Use rest parameters and spread together.

// Write mergeTags(...lists)

09Prediction

Commit to an answer first, then run the real code to compare.

const a = { x: 1, y: 2 };
const b = { y: 9, ...a };
console.log(b.y);

What is printed?

10Debugging investigation

Undo history changes when the draft changes

The editor saves a snapshot before editing, but the snapshot changes too, so undo shows the edited tags.

const draft = { title: "Report", tags: ["draft"] };
const snapshot = { ...draft };
draft.tags.push("urgent");
console.log(`Snapshot tags: ${snapshot.tags}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Immutable state updates

Interface frameworks compare old and new state objects to decide what to redraw. Updating with spread produces a new object each time, so the change is easy to detect and the old state is kept for undo.

const state = { count: 1, history: [] };
const next = { ...state, count: state.count + 1, history: [...state.history, state.count] };
console.log(state, next);

12Knowledge check

1. What is printed?

const a = [1, 2];
console.log([...a, 3]);
  • [1, 2, 3]
  • [[1, 2], 3]
  • [1, 2, [3]]
  • An error

2. What is printed?

const [first, ...rest] = [1, 2, 3];
console.log(rest);
  • 3
  • 1
  • [2, 3]
  • [1, 2, 3]

3. What kind of copy does { ...obj } make?

  • Deep
  • Shallow
  • None, it is the same object
  • A string

4. Why is this a SyntaxError?

const [...items, last] = [1, 2, 3];
  • Rest must be last
  • Arrays cannot be destructured
  • last is reserved
  • Missing semicolon

5. What is printed?

console.log(Math.max(...[1, 5, 3]));
  • 3
  • [1, 5, 3]
  • 5
  • NaN

6. To add an item to a cart stored in state, which is safer?

  • state.cart.push(item)
  • state = { ...state, cart: [...state.cart, item] }
  • state.cart[state.cart.length] = item
  • delete state.cart

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the nested array: Prints 3; day is flat
  • Toggle a setting immutably: Prints light dark; Keeps other settings; A new object
  • Merge tag lists: Prints unique tags; No lists gives []; Inputs unchanged
  • ex-042-01: output matches the documented expected output
  • ex-042-02: output matches the documented expected output
  • ex-042-03: output matches the documented expected output
  • ex-042-04: output matches the documented expected output
  • ex-042-05: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-09-modern-javascript-syntax/lesson-042-spread-and-rest-syntax/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • Spread expands arrays and objects into new ones.
  • Later object properties win.
  • Rest collects remaining arguments, items or properties.
  • Spread copies are shallow.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation spread and rest syntax
Context: I am learning spread and rest syntax in JavaScript.
Task: Explain the difference between spread and rest with shopping cart examples.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction spread and rest syntax drill
Context: I have practised spread and rest syntax.
Task: Give me six snippets mixing spread, rest and property order and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging spread and rest syntax bug
Context: My copy made with spread still changes the original.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation spread and rest syntax practice
Context: I finished the spread and rest syntax exercises.
Task: Create three exercises that update state immutably with spread.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review spread and rest syntax review
Context: Here is my code that uses spread and rest syntax.
Task: Review my code for mutations that spread could replace, and for shallow-copy mistakes.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.