Do you think IIT Guwahati certified course can help you in your career?
No
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.
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:
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);
You can also try this code with Online Javascript Compiler
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);
You can also try this code with Online Javascript Compiler
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);
You can also try this code with Online Javascript Compiler
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));
You can also try this code with Online Javascript Compiler
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.
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);
You can also try this code with Online Javascript Compiler
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.
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.