ES6- Spread Operator
Spread Operator(...) in ES6
Using the Spread Operator, you can copy a part of an existing array into another array.
The spread operator, one of new feature added in the JavaScript ES6 version.
<script> const arr1 = ['a', 'b', 'c']; const arr2 = ['d', 'e', 'f']; const arrCombined = [...arr1, ...arr2]; document.write(arrCombined); </script>
The spread operator with destructuring.
Example
Assign the first and second items from numbers to variables and put the rest in an array:
const arr1 = [1, 2, 3, 4, 5, 6];
const [one, two, ...rest] = arr1;
spread operator with functions
If 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.
Example,
let func1 = function(...args) {
console.log(args);
}
func1(3); // [3]
func1(4, 5, 6); // [4, 5, 6]
Example2,
function sum(x, y ,z) {
console.log(x + y + z);
}
const arr1= [1, 3, 4, 5];
sum(...arr1); // 8
ES6 HOME
Comments
Post a Comment