Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 58

Expanding with the Spread Operator

This lesson is built with resources from youtube.com, dev.to and 1 more site.

Hello! In our last lesson, we saw how the three dots (...) can be used as a rest parameter to collect multiple elements into a single array. Now, we're going to explore the other, more common, identity of this versatile syntax: the spread operator.

Today's lesson is all about using the spread operator to expand or "unpack" the elements from arrays and objects. This is the opposite of the rest parameter. Your goal is to apply the spread operator (...) to expand elements from arrays and objects. This is a fundamental technique in modern JavaScript that you will use constantly to create copies of data and combine data structures, especially when managing application state in Next.js.

What is the Spread Operator?

At its core, the spread operator ... takes a collection (like an array or object) and spreads its individual elements out.

Imagine an array is a box holding several items.

  • Without spread, you pass the whole box around.
  • With spread, you open the box and lay all the items out individually.
Visualizing the Spread Operator with Arrays
This image visually captures the essence of the spread operator: it takes a container (the array `[1, 2, 3]`) and expands its contents into individual elements (`1, 2, 3`).

To get a feel for this "unpacking" idea, let's watch a short, beginner-friendly introduction.

JavaScript Magic Trick You Need to Know! | JavaScript Spread Operator

This video from Nova Designs uses a great 'backpack' analogy to introduce the concept of the spread operator. Watch this first segment to understand what 'spreading' means in practice.

Watch from the beginning to 01:26. Notice the difference in the console.log output when the array is logged normally versus when it's logged with the spread operator. This is the core concept of 'unpacking'.

As the video shows, ...[1, 2, 3] is treated as 1, 2, 3. This simple idea is incredibly powerful. But why is it so important? The answer lies in a core concept of programming: immutability.


The "Why": Immutability and Creating Safe Copies

You've learned that JavaScript has primitive types (like strings and numbers) and reference types (objects and arrays). When you assign a primitive type, you copy its value. But when you assign a reference type, you only copy a reference (or a pointer) to the same object in memory. This can cause unexpected bugs.

Let's read a fantastic explanation that uses a Pokémon analogy to make this crystal clear.

Understanding the JavaScript Spread Operator

This article from dev.to explains the critical problem that the spread operator solves. It will give you that 'deep theory' understanding of why this is a 'must-know' feature.

Read the sections 'Introduction' and 'Why you should use the spread operator'. Focus on the Squirtle example. It perfectly illustrates how changing a 'copy' of an object can accidentally change the original, a problem called mutation.

As the article explained, simply assigning an array or object to a new variable (let newArray = oldArray) does not create a new array. It just creates another label pointing to the same array.

The spread operator solves this by creating a true copy. When you write const newArray = [...oldArray], you are:

  1. Creating a brand new, empty array [].
  2. Taking the oldArray, unpacking all of its elements with ....
  3. Placing those unpacked elements inside the new array.

This ensures that your new array is a separate entity, and changes to it won't affect the original. This principle is called immutability—treating data as unchangeable and creating new data instead of modifying existing data. This is a cornerstone of modern frameworks like Next.js.

Now, let's see a detailed video walkthrough of this exact concept.

#44 What is the Spread Operator? | JavaScript Full Tutorial

The following clip from Dev Dreamer provides a fantastic visual demonstration of creating copies versus creating references. It will solidify your understanding of immutability.

Watch from 00:45 to 07:56. Pay close attention to: The difference between let secondArray = characters and let updatedCharacters = [...characters]. What happens when you use a method like .push() or .pop() on a reference versus on a true copy. How this applies to combining arrays.

A Quick Note on "Shallow" Copies: The spread operator performs a shallow copy. This means if your array or object contains other arrays or objects inside it (nested data), those nested structures are still copied by reference. For now, just be aware of this. We will explore deep copies later when we need them.


Common Uses of the Spread Operator

Now that you understand the "what" and the "why," let's look at the most common ways you'll apply the spread operator.

1. Combining Arrays and Objects

You can easily merge multiple arrays or objects into one. The operator unpacks each one, and the surrounding [] or {} gathers all the elements into a new structure.

Spread Operator in JavaScript: Array Concatenation
This image shows a practical code example of merging two arrays. The elements from `arr4` are 'spread' into `arr3` to form a new, combined array.
// Combining ARRAYS
const fruits = ["apple", "banana"];
const vegetables = ["broccoli", "carrot"];

const food = [...fruits, ...vegetables];
console.log(food); // ["apple", "banana", "broccoli", "carrot"]

// Combining OBJECTS
const userProfile = {
  name: "Alex",
  username: "alex123"
};
const userSettings = {
  theme: "dark",
  notifications: true
};

const user = { ...userProfile, ...userSettings };
console.log(user); 
// { name: "Alex", username: "alex123", theme: "dark", notifications: true }

If objects have the same property key, the property from the object that is spread later will overwrite the earlier one.

const defaults = { status: "active", theme: "light" };
const userPrefs = { theme: "dark", timezone: "UTC" };

const finalSettings = { ...defaults, ...userPrefs };
// The `theme` from `userPrefs` overwrites the one from `defaults`
console.log(finalSettings); 
// { status: "active", theme: "dark", timezone: "UTC" }

2. Adding New Elements (Immutably)

This is a core pattern in state management for Next.js and React. Instead of pushing an item to an existing array (mutating it), you create a new array that includes the old items plus the new one.

const tasks = ["Buy groceries", "Walk the dog"];

// Add a new task to the end
const newTasks = [...tasks, "Pay bills"];
console.log(newTasks); // ["Buy groceries", "Walk the dog", "Pay bills"]

// Add a new task to the beginning
const newTasksFirst = ["Check email", ...tasks];
console.log(newTasksFirst); // ["Check email", "Buy groceries", "Walk the dog"]

// Add a new property to an object
const book = { title: "The Hobbit", author: "J.R.R. Tolkien" };
const bookWithId = { id: 1, ...book };
console.log(bookWithId); // { id: 1, title: "The Hobbit", author: "J.R.R. Tolkien" }

3. Passing Array Elements as Function Arguments

Some functions, like Math.max(), expect a list of individual arguments, not a single array. The spread operator is perfect for this.

const numbers = [10, 5, 25, 18];

// This will NOT work, Math.max expects Math.max(10, 5, 25, 18)
const maxWrong = Math.max(numbers);
console.log(maxWrong); // NaN (Not a Number)

// This WORKS because spread unpacks the array into individual arguments
const maxCorrect = Math.max(...numbers);
console.log(maxCorrect); // 25

For more examples on all these use cases, you can refer to this handy guide.

Free JavaScript Rest and Spread Tutorial for Beginners

This tutorial from iqratechnology provides clear, concise examples for using the spread operator with both arrays and objects.

Focus on the sections titled 'The Spread Operator (Unpacking Data)', 'Example 1: Spread Operator in Arrays', and 'Example 2: Spread Operator with Objects'. You can also scan the 'Frequently Asked Questions' at the end for quick summaries of the main use cases.

Test your understanding!

You have an original product object. A customer wants to buy it and add it to their cart. Your task is to create a productInCart object that contains all the properties of the original product, but with two changes:

  1. The status should be changed to "in cart".
  2. A new property, quantity, should be added with a value of 1.

The original product object must not be changed.

const product = {
  id: "xyz-789",
  name: "Wireless Mouse",
  price: 25.99,
  status: "available"
};

// Your code here to create `productInCart`

// console.log(productInCart);
// console.log(product); // Should be unchanged
Show answer
const product = {
  id: "xyz-789",
  name: "Wireless Mouse",
  price: 25.99,
  status: "available"
};

const productInCart = { 
  ...product, 
  status: "in cart", 
  quantity: 1 
};

console.log(productInCart);
/* Output:
{
  id: "xyz-789",
  name: "Wireless Mouse",
  price: 25.99,
  status: "in cart",
  quantity: 1
}
*/

console.log(product);
/* Output (unchanged):
{
  id: "xyz-789",
  name: "Wireless Mouse",
  price: 25.99,
  status: "available"
}
*/

Explanation:

  1. We start creating a new object {...}.
  2. ...product spreads all the key-value pairs from the original product object into this new object.
  3. status: "in cart" adds a status property. Because this comes after the spread, it overwrites the original status property.
  4. quantity: 1 adds a brand new property to the object.
  5. The original product object is never modified directly, demonstrating immutability.

Conclusion

You've now seen both sides of the ... syntax! It's a powerful tool that changes its behavior based on context:

  • When used in a function's parameter list or on the left side of a destructuring assignment, it's the rest parameter that gathers elements into an array.
  • When used on the right side of an assignment or in a function call, it's the spread operator that expands an iterable's elements.

Key Takeaways:

  • The spread operator (...) "unpacks" elements from arrays and properties from objects.
  • Its primary use is to create immutable copies and combinations of arrays and objects. This is crucial for predictable code and is a fundamental pattern in Next.js/React.
  • You can use it to combine multiple arrays/objects, add new elements/properties, and pass array elements as function arguments.

Next Up

In the next lesson, we will formalize our understanding of the rest parameter (...), focusing on how it allows us to create flexible functions that can accept a variable number of arguments. This will complete your mastery of the versatile ... syntax.