JavaScript Spread Operator Tutorial with Examples

The spread operator (…) in JavaScript is a powerful and versatile tool that allows you to expand an array, object, or iterable into individual elements or properties.

It is commonly used to make working with arrays, objects, and function arguments more efficient and concise.

In this tutorial, you’ll learn:

What is the spread operator?
Using the spread operator with arrays
Using the spread operator with objects
Using the spread operator with function arguments
Practical examples of the spread operator

1. What is the Spread Operator?

The spread operator (…) is used to expand elements in an array or properties in an object into individual items. It can be used in various situations, such as copying arrays or objects, combining arrays, or passing elements to functions as arguments.

Syntax:

...iterable

Iterable: Any object that can be iterated over (e.g., arrays, strings, sets).

2. Using the Spread Operator with Arrays

The spread operator is frequently used with arrays for a variety of operations such as copying, concatenation, and destructuring.

Example 1: Copying an Array

You can create a shallow copy of an array using the spread operator.

const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];

console.log(copiedArray);  // Output: [1, 2, 3]

In this example, copiedArray is a new array with the same elements as originalArray. The spread operator creates a shallow copy, meaning it only copies the top-level elements.

Example 2: Concatenating Arrays

You can combine or merge arrays easily using the spread operator.

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = [...array1, ...array2];

console.log(combinedArray);  // Output: [1, 2, 3, 4, 5, 6]

The spread operator allows you to concatenate arrays without using Array.prototype.concat().

Example 3: Adding Elements to an Array

You can add elements to an array at specific positions using the spread operator.

const numbers = [1, 2, 3];
const newNumbers = [0, ...numbers, 4, 5];

console.log(newNumbers);  // Output: [0, 1, 2, 3, 4, 5]

In this example, 0 is added at the beginning, and 4 and 5 are added at the end.

Example 4: Using Spread Operator with Array Destructuring

The spread operator works well with destructuring to split arrays into individual variables.

const numbers = [1, 2, 3, 4, 5];

// Destructuring with spread
const [first, second, ...rest] = numbers;

console.log(first);  // Output: 1
console.log(second);  // Output: 2
console.log(rest);  // Output: [3, 4, 5]

In this example, first gets the value 1, second gets the value 2, and the rest variable holds the remaining elements [3, 4, 5].

3. Using the Spread Operator with Objects

The spread operator can also be used with objects to copy or merge properties from one object to another. This feature was introduced in ES2018 (ES9).

Example 5: Copying an Object

You can create a shallow copy of an object using the spread operator.

const originalObject = { name: "Alice", age: 25 };
const copiedObject = { ...originalObject };

console.log(copiedObject);  // Output: { name: 'Alice', age: 25 }

Here, copiedObject is a new object with the same properties as originalObject.

Example 6: Merging Objects

You can merge multiple objects using the spread operator.

const obj1 = { name: "Alice", age: 25 };
const obj2 = { age: 30, city: "New York" };

const mergedObject = { ...obj1, ...obj2 };

console.log(mergedObject);  // Output: { name: 'Alice', age: 30, city: 'New York' }

In this example:

The age property from obj2 overwrites the age property from obj1 since it appears later in the merge process.
The final object contains properties from both objects.

Example 7: Adding or Modifying Properties in an Object

You can use the spread operator to add or update properties in an object.

const user = { name: "Alice", age: 25 };
const updatedUser = { ...user, age: 26, city: "Paris" };

console.log(updatedUser);  // Output: { name: 'Alice', age: 26, city: 'Paris' }

In this case:

The age property is updated to 26.
A new property city is added with the value “Paris”.

Example 8: Nested Object Spread (Shallow Copy)

The spread operator performs a shallow copy, meaning it does not copy nested objects deeply.

const originalObject = { name: "Alice", address: { city: "Paris" } };
const shallowCopy = { ...originalObject };

shallowCopy.address.city = "London";

console.log(originalObject.address.city);  // Output: 'London'
console.log(shallowCopy.address.city);     // Output: 'London'

Both originalObject and shallowCopy still reference the same nested object (address), so modifying it affects both objects.

4. Using the Spread Operator with Function Arguments

The spread operator can be used to pass elements of an array as individual arguments to a function. This is particularly useful when working with functions that take multiple arguments.

Example 9: Passing Array Elements as Function Arguments

function add(a, b, c) {
    return a + b + c;
}

const numbers = [1, 2, 3];

console.log(add(...numbers));  // Output: 6

In this example, the spread operator expands the array numbers into individual arguments (1, 2, 3) and passes them to the add() function.

Example 10: Using Spread Operator with Math.max()

The Math.max() function can take any number of arguments, and the spread operator can be used to pass an array of numbers.

const numbers = [10, 20, 30, 40, 50];
const maxNumber = Math.max(...numbers);

console.log(maxNumber);  // Output: 50

The spread operator expands the numbers array into individual elements, allowing Math.max() to evaluate them.

5. Practical Examples of the Spread Operator

Example 11: Removing Duplicates from an Array

You can use the spread operator in combination with the Set object to remove duplicates from an array.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers);  // Output: [1, 2, 3, 4, 5]

In this example, the Set removes duplicates, and the spread operator converts the set back into an array.

Example 12: Cloning Arrays and Objects

The spread operator is useful for making shallow copies of arrays and objects.

// Array clone
const originalArray = [1, 2, 3];
const clonedArray = [...originalArray];

clonedArray.push(4);
console.log(originalArray);  // Output: [1, 2, 3]
console.log(clonedArray);    // Output: [1, 2, 3, 4]

// Object clone
const originalObject = { name: "Alice", age: 25 };
const clonedObject = { ...originalObject };

clonedObject.age = 26;
console.log(originalObject);  // Output: { name: 'Alice', age: 25 }
console.log(clonedObject);    // Output: { name: 'Alice', age: 26 }

In this case, the spread operator creates a shallow copy, meaning that top-level elements are copied but nested objects or arrays still reference the same memory.

Example 13: Combining Default and Custom Properties

You can use the spread operator to combine default properties with custom properties for more flexible object creation.

const defaultSettings = { theme: "light", notifications: true, language: "en" };
const userSettings = { theme: "dark", language: "fr" };

const combinedSettings = { ...defaultSettings, ...userSettings };

console.log(combinedSettings);
// Output: { theme: 'dark', notifications: true, language: 'fr' }

In this example, the properties from userSettings override those in defaultSettings.

Conclusion

The spread operator (…) in JavaScript is a powerful and flexible tool that simplifies working with arrays, objects, and function arguments. Here's a summary of what you've learned:

The spread operator can be used to copy arrays and objects, merge them, and add new elements or properties.
It is useful for passing function arguments from arrays and removing duplicates from arrays.
It allows for shallow cloning of objects and arrays, making it easy to handle data efficiently.

With the spread operator, you can write cleaner, more concise, and more maintainable JavaScript code. Now you're equipped to start using it effectively in your projects!

Related posts

JavaScript typeof Operator Tutorial with Examples

JavaScript Grouping Operator Tutorial with Examples

JavaScript Comma Operator Tutorial with Examples