JavaScript Spread Operator
JavaScript Spread Operator
Spread Operator
The spread operator ... is used to expand or spread an iterable or an array.
For example,
const arrValue = ['My', 'name', 'is', 'Jack'];
console.log(...arrValue)
is equivalent to:
console.log(arr2);
// Output:
// ["one", "two", "three", "four", "five"]
Run Code
Clone Array Using Spread Operator
In JavaScript, objects are assigned by reference and not by values. For
example,
console.log(arr1); // [1, 2, 3]
console.log(arr2); // [1, 2, 3]
console.log(arr1); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 3, 4]
Run Code
Here, both variables arr1 and arr2 are referring to the same array. Hence the
change in one variable results in the change in both variables.
However, if you want to copy arrays so that they do not refer to the same
array, you can use the spread operator. This way, the change in one array is
not reflected in the other. For example,
console.log(arr1); // [1, 2, 3]
console.log(arr2); // [1, 2, 3]
console.log(arr1); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 3]
Run Code
Spread Operator with Object
You can also use the spread operator with object literals. For example,
const obj1 = { x : 1, y : 2 };
const obj2 = { z : 3 };
console.log(obj3); // {x: 1, y: 2, z: 3}
Run Code
Here, both obj1 and obj2 properties are added to obj3 using the spread
operator.
Rest Parameter
When the spread operator is used as a parameter, it is known as the rest
parameter.
You can also accept multiple arguments in a function call using the rest
parameter. For example,
func(3); // [3]
func(4, 5, 6); // [4, 5, 6]
Run Code
Here,
When a single argument is passed to the func() function, the rest
parameter takes only one parameter.
When three arguments are passed, the rest parameter takes all three
parameters.
Note: Using the rest parameter will pass the arguments as array elements.
You can also pass multiple arguments to a function using the spread operator.
For example,
sum(...num1); // 8
Run Code
If you pass multiple arguments using the spread operator, the function takes
the required arguments and ignores the rest.
Note: Spread operator was introduced in ES6. Some browsers may not
support the use of spread syntax. Visit JavaScript Spread Operator support to
learn more.