Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Spread Operator
2.1.
Syntax 
3.
Concat() method
3.1.
Example
4.
Copying the Array
4.1.
Example
5.
Expanding the Array 
5.1.
Example
6.
Math Objects 
6.1.
Example
7.
Spread Operator and Objects
7.1.
Example
8.
Rest Parameter
8.1.
Example
9.
Frequently Asked Questions
9.1.
What is a spread operator in Javascript?
9.2.
When to use the spread operator in JavaScript?
9.3.
What is the spread and rest operator in JS?
9.4.
How to spread a string in JavaScript?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Spread Operator in Javascript

Author Sohail Ali
3 upvotes
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

The spread operator is the latest addition to the set of operators in JavaScript ES6. It expands an iterable into its component parts. In order to create deep copies of JS objects, the spread operator is frequently employed. The rest operator makes code more readable whenever used.

Spread Operator in Javascript

In this blog, we will look at spread operators in javascript and explore their functionalities.

Spread Operator

The spread operator is provided by ES6 and consists of three dots (...). You can spread elements from an iterable object, such as an array, map, or set, using the spread operator in JavaScript.

Syntax 

var <variable_name> = [ …<values>];

 

  • var is a keyword used to declare a variable in JavaScript. It has a function scope.
     
  • <variable_name> is a placeholder for the name you want to assign to the variable.
     
  • The = is the assignment operator used to assign a value to the declared variable.
     
  • The [...<values>] syntax denotes an array. <values> is a placeholder for the actual values you want to put in the array. The ... is the spread syntax (or spread operator) used to expand iterable elements.
     

The spread syntax (...) is used to unpack elements from arrays or properties from objects into distinct variables. It can be used in function calls, array literals, or object literals. It's a more modern feature in JavaScript, included as part of the ECMAScript 2015 (ES6) update.

Let’s explore the different methods of Spread operator in Javascript:

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Concat() method

We can use the spread operator in javascript to concatenate all the items in a single array.

Example

// Creating arrays
let arr1 = [1, 2, 3];
let arr2 = [4, 5];
let arr3 = [6, 7];

// Concatenating array using the spread operator
arr = [...arr1, ...arr2, ...arr3];
console.log("New Array Elements: ")
console.log(arr);


Output

Concatenating arrays output

Explanation

In the above code of the spread operator in Javascript, all the values of arr1, arr2, and arr3 will get copied into arr. Any changes made in any of the three arrays will not be reflected in the new array.

Note: It is recommended to use the concat() method instead of the spread operator for faster execution speed of large data.

Copying the Array

The Spread operator can be used to copy the contents of one array into another array.

Example

// Creating array
let array1 = ["apple", "bat", "cat"];
// Copying the contents
let array2 = [...array1];

// Printing the arrays
console.log(array1);
console.log(array2);
console.log();

// Adding elements in array1
array1.push("Dog");
console.log("After changing array1:");
console.log(array1);
console.log(array2);


Output 

Copying the Array output

Explanation

In the above code of spread operator in Javascript, the contents of array1 are copied into array2, and changing array1 did not affect array2 when we use spread operators.

Expanding the Array 

We can expand a single array without copying one array inside another array using the spread operator in Javascript.

Example

// Creating an array
let array1 = ["apple", "bat", "cat"];
// Expanding the array
let array2 = [...array1, "Dog", "Egg"];

// Printing the arrays
console.log(array1);
console.log(array2);


Output

Expanding the Array output

Explanation

In the above code of spread operator in Javascript, the array2 is created using contents of array1, and some added contents.

Math Objects 

The math objects method doesn’t work with arrays and will return NaN output.

Example

let arr = [2, 5, 2, 8, 22, 20];
// Finding the maximum element
console.log(Math.max(arr)); 


Output 

NaN


All the methods in the math object do not work with arrays directly and will return a NaN value. But we can avoid this using a spread operator in Javascript.

Now, let's see what output we will get after using the spread operator.

let arr = [2, 5, 2, 8, 22, 20];
// Finding the maximum element
console.log(Math.max(...arr)); 


Output

22


Explanation

Instead of NaN, we are getting the correct answer using the spread operator. This is because whenever we use the spread operator, it expands the array into a list to avoid the NaN result.

Spread Operator and Objects

We can use the spread operator in Javascript to spread an object and create another object with the same details in the key-value pair.

Example

// Student details
const student1 = {
    name: 'Vidhi',
    batch: 'B2',
    roll: 53,
    age: 21,
};

// Creating a duplicate object
const duplicate_obj = { ...student1 };

console.log('Original Object');
console.log(student1);

console.log('Cloned Object');
console.log(duplicate_obj);


Output

Spread operator and Objects

Explanation 

In this code, the student1 object is spread using the spread operator, and another object named duplicate_obj is created using the details of the student1 object. Both of these original (student1) and cloned (duplicate_obj) objects will have the same properties.

Rest Parameter

Let us see the behavior of the spread operator when multiple arguments are passed to a function.

Example

// function to multiply three numbers
function multiply(x, y, z) {
    console.log(x * y * z);
}

const arr = [2, 5, 5, 4, 5];

multiply(...arr);


Output

50


Explanation

In the above code of the spread operator in Javascript, the function multiply only considers the required parameter and ignores the rest of them whenever arguments are passed using the spread operator.

A rest parameter comes into play whenever we want to pass and access multiple parameters through a function. A rest parameter is simply a spread operator passed as a parameter.

Must Read Fibonacci Series in JavaScript

Frequently Asked Questions

What is a spread operator in Javascript?

A spread operator in Javascript is written using three dots ( … ) to expand an iterable object into the list of arguments.

When to use the spread operator in JavaScript?

The spread operator in JavaScript is used to unpack elements from arrays or properties from objects. It's often employed to copy arrays, merge arrays or objects, spread an array into function arguments, or transform a string into an array of characters.

What is the spread and rest operator in JS?

The spread operator (`...`) in JavaScript unpacks elements from arrays or properties from objects, which is useful for merging or copying collections. The rest operator also uses `...`, but in function parameters to capture an indefinite number of arguments into an array.

How to spread a string in JavaScript?

To spread a string in JavaScript, use the spread operator (`...`) within an array. This will split the string into individual characters. For instance: `let chars = [..."Hello"];` results in `chars` being `['H', 'e', 'l', 'l', 'o']`.

Conclusion

This article discusses the spread operator in Javascript, along with multiple examples. We hope this blog has helped you enhance your knowledge of spread operators in Javascript. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your coding ability, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

Previous article
Operators in Javascript
Next article
JavaScript Ternary Operator
Live masterclass