JavaScript Spread Operator
Last Updated :
11 Nov, 2024
The Spread operator (represented as three dots or …) is used on iterables like array and string, or properties of Objects. to expand wherever zero or more elements are required top be copied or assigned. Its primary use case is with arrays, especially when expecting multiple values. The syntax of the Spread operator is the same as the Rest parameter but it works opposite of it.
1. Adding Multiple Elements Using Spread Operator
Even though we get the content on one array inside the other one, actually it is an array inside another array which is definitely what we didn’t want. If we want the content to be inside a single array we can make use of the spread operator.
javascript
// expand using spread operator
let a = [10, 20];
let b = [...a, 30, 40];
console.log(a);
We can insert at the beginning and both begin and end together also
JavaScript
// expand using spread operator
let a = [10, 20];
let b = [30, 40, ...a, 50, 60];
console.log(a);
2. Find Min / Max using Spread Operator
Math object method won’t work and will return NaN. When …arr is used in the function call, it “expands” an iterable object arr into the list of arguments In order to avoid this NaN output, we make use of a spread operator. we make use of a spread operator In order to avoid this NaN
javascript
// Min in an array using Math.min()
let a = [1,2,3,-1];
console.log(Math.min(a)); //NaN
// Now using spread
console.log(Math.min(...a));
3. Passing Array Elements as Function Parameters
JavaScript
function add(x, y, z) {
return x + y + z;
}
let a = [10, 20, 30];
console.log(add(...a));
4. Copying Array using Spread
We are copying all the elements of the given array to the another new array by the use of the spread operator.
JavaScript
const a = [1, 2, 3];
const b = [...a];
console.log(b);
// Please note that in JavaScript, doing
// b = a does not create a clone. It only creates
// one more reference. You may try uncommening the
// below code
// const c = [1, 2, 3];
// const d = c;
// d.push(4);
// console.log(c); // Prints [1, 2, 3, 4]
Please refer Clone an array for different methods of copying an array in JS
5. Concatenate Arrays using Spread Operator
The spread operator can be used to concatenate more than one array.
javascript
// Spread operator for array concatenation
let a = [1, 2, 3];
let b = [4, 5];
a = [...a, ...b];
console.log(a);
Note: Though we can achieve the same result as the concat method, it is not recommended to use the spread in this particular case, as for a large data set it will work slower when compared to the native concat() method.
6. Working of Objects with Spread Operator
ES6 has added spread property to object literals in javascript. The spread operator (…) with objects is used to create copies of existing objects with new or updated values or to make a copy of an object with more properties. Let’s take an example of how to use the spread operator on an object,
javascript
const usr = {
name: 'Jen',
age: 22
};
const cloneUsr = { ...usr };
console.log(cloneUsr);
Output{ name: 'Jen', age: 22 }
Here we are spreading the usr object. All key-value pairs of the usr object are copied into the cloneUsr object.
Let’s look at another example of merging two objects using the spread operator.
javascript
const usr1 = {
name: 'Jen',
age: 22,
};
const usr2 = {
name: "Andrew",
location: "Philadelphia"
};
const mergedUsers = { ...usr1, ...usr2 };
console.log(mergedUsers);
Output{ name: 'Andrew', age: 22, location: 'Philadelphia' }
The mergedUsers is a copy of usr1 and usr2. Actually, every enumerable property on the objects will be copied to the mergedUsers object. The spread operator is just a shorthand for the Object.assign() method but, there are some differences between the two.
Below is an example of adding properties to an object using spread operator.
JavaScript
const o1 = { a: 1, b: 2 };
const o2 = { ...o1, b: 3, c: 4 };
console.log(o2);
Output{ a: 1, b: 3, c: 4 }
We have a complete list of Javascript Operators, to check those please go through the Javascript Operators Complete Reference article.
Similar Reads
JavaScript String Operators
JavaScript String Operators are used to manipulate and perform operations on strings. There are two operators which are used to modify strings in JavaScript. These operators help us to join one string to another string. 1. Concatenate OperatorConcatenate Operator in JavaScript combines strings using
3 min read
Spread vs Rest operator in JavaScript ES6
Rest and spread operators may appear similar in notation, but they serve distinct purposes in JavaScript, which can sometimes lead to confusion. Let's delve into their differences and how each is used. Rest and spread operators are both introduced in javascript ES6. Rest OperatorThe rest operator is
2 min read
ES6 Spread Operator
Spread Operator is a very simple and powerful feature introduced in the ES6 standard of JavaScript, which helps us to write nicer and shorter code. The JavaScript spread operator is denoted by three dots (...). The spread operator helps the iterable objects to expand into individual elements. Iterab
3 min read
JavaScript Comma Operator
JavaScript Comma Operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. [GFGTABS] JavaScript let x = (1, 2, 3); console.log(x); [/GFGTABS]Output3 Here is another example to show that all expressions are actually executed. [GFGTABS] Java
2 min read
JavaScript Remainder Assignment(%=) Operator
JavaScript remainder assignment operator (%=) assigns the remainder to the variable after dividing a variable by the value of the right operand. Syntax: Operator: x %= y Meaning: x = x % y Below example illustrate the Remainder assignment(%=) Operator in JavaScript: Example 1: The following example
1 min read
JavaScript Addition (+) Operator
JavaScript addition (+) operator is one of the most fundamental and widely used arithmetic operators in JavaScript. It is used to perform arithmetic addition on numbers but also concatenate strings. Syntaxa + bWhere - a: The first value (number, string, or another data type).b: The second value (num
1 min read
JavaScript Spread Syntax (...)
The spread syntax is used for expanding an iterable in places where many arguments or elements are expected. It also allows us the privilege to obtain a list of parameters from an array. The spread syntax was introduced in ES6 JavaScript. The spread syntax lists the properties of an object in an obj
4 min read
JavaScript Operators Coding Practice Problems
Operators in JavaScript allow you to perform operations on variables and values, including arithmetic, logical, bitwise, comparison, and assignment operations. Mastering JavaScript operators is essential for writing efficient expressions and conditional statements. This curated list of JavaScript op
1 min read
Subtraction(-) Arithmetic Operator in JavaScript
JavaSscript arithmetic subtraction operator is used to find the difference between operators after subtracting them. Depending on the nature of the two operands, the subtraction operator performs either number subtraction or BigInt subtraction after converting both operands to numeric values. Syntax
1 min read
How Spread Operator Works in JS
The spread operator (...) in JavaScript is a powerful feature used to expand or spread elements of an iterable (like an array or object) into individual elements. It is commonly used in situations where you want to copy or merge arrays, objects, or even pass arguments to functions. 1. Arrays with th
3 min read