Master the JavaScript Spread Operator with Simple Examples

JavaScript’s spread operator (...) is one of the most powerful and flexible features introduced in ES6. It allows us to quickly expand or spread elements from an array, object, or string into individual elements or key-value pairs. It is represented by three dots (...) and is often used to make working with arrays and objects easier and cleaner. In this article we will learn about spread operator in Javascript with a lot of code examples.

What is the Spread Operator in JavaScript?

The spread operator (...) allows you to expand elements of an iterable (like an array or object) into individual elements.

Lets’s have a look at the syntax.

const newArray = [...existingArray];
const newObject = { ...existingObject };

The spread operator unpacks the values of an array or object and spreads them wherever the value is expected.

Lets’s have a look at various use cases or examples of Spread Operator.

Copying an Array

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

const fruits = ["apple", "banana", "orange"];
const newFruits = [...fruits];

newFruits.push("mango");

console.log("Original:", fruits); // ["apple", "banana", "orange"]
console.log("New:", newFruits);   // ["apple", "banana", "orange", "mango"]

When you see the output in the browser console you will see newFruits will create a new array with same value as fruits. Also newFruits is a copy of fruits so modifying newFruits doesn’t affect fruits.

Merging Arrays

You can combine arrays using spread operator. Let’s have a look at the code example.

const firstSet = [1, 2, 3];
const secondSet = [4, 5, 6];

const combined = [...firstSet, ...secondSet];
console.log(combined); // [1, 2, 3, 4, 5, 6]

In the above example we have combined two arrays in to one. We can also add custom values between them. Have a look at the code below.

const combined = [...firstSet, 99, ...secondSet];
console.log(combined); // [1, 2, 3, 99, 4, 5, 6]

Copying and Updating Objects

Using Spread operator we can easily create a copy of an object or update existing properties.

const user = { name: "John", age: 30 };
const updatedUser = { ...user, age: 31, city: "New York" };

console.log(updatedUser); 
// { name: "John", age: 31, city: "New York" }

The above code creates a new object using the values from the user object. If a key already exists then the value is updated like age in the above example and if the key doesn’t exists then the key value pair is added to the object.

Passing Values to a Function

Yes you read it right we can pass values to a function using a spread operator.

const nums = [1, 2, 3];

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

console.log(sum(...nums)); // 6

In the above code snippet the ...nums spreads the array elements into individual function arguments.

I have a challenge for you tell me what will happen when we give fewer or more values while calling the function. Try [5, 10] or [1, 2, 3, 4] — does it work?

Working with Strings

Do you know strings are iterables and hence spread operator works with strings as well.

const greeting = "Hello";
const characters = [...greeting];

console.log(characters); // ["H", "e", "l", "l", "o"]

Each character in the string is treated as an array element.

Nested Objects and Arrays (Shallow vs Deep Copy)

Spread operator creates a shallow copy — it doesn’t work for deeply nested structures.

const person = {
  name: "John",
  address: {
    city: "New York"
  }
};

const shallowCopy = { ...person };
shallowCopy.address.city = "Los Angeles";

console.log(person.address.city); // "Los Angeles" 

As i told you spread operator doesn’t work with nested objects. So if you tried to change any nested properties in the newly created object the property of the old objects are effected as well.

The spread operator only creates a shallow copy. It copies top-level properties but nested objects are still referenced. To fix this, you need a deep copy

In order to resolve this issue we can use structuredClone(). Copy the below code in your editor and see the logs in browser console.

const person = {
  name: "John",
  address: {
    city: "New York"
  }
};

const deepCopy = structuredClone(person);
deepCopy.address.city = "Los Angeles";

console.log(person.address.city); // "New York"

Spread with Arrays as Objects

An array is technically an object, so you can spread it into an object:

const arr = [1, 2, 3];
const obj = { ...arr };

console.log(obj); 
// { 0: 1, 1: 2, 2: 3 }

Spread in Function Return Values

You can return values from a function using spread:

function getColors() {
  return ["red", "green", "blue"];
}

const colors = ["yellow", ...getColors(), "pink"];
console.log(colors); 
// ["yellow", "red", "green", "blue", "pink"]

In the above code ...getColors() expands the returned array into individual elements.

I think we have covered lot of use cases and examples of the spread operator. I hope now you know about spread operator in detail and can use it to write clean code. If you have any doubts then let us know in the comments.

Leave a Comment