Rest and Spread Operators in JavaScript
The rest and spread operators are new features in ES6 that provide a way to work with arrays and objects more easily.
Here's an example of how to use the rest operator to create a function that accepts any number of arguments:
javascript
Copy code
function sum(...numbers) {
return numbers.reduce(function(a, b) {
return a + b;
});
}
console.log(sum(1, 2, 3, 4, 5)); // prints 15
The ...numbers syntax is the rest operator, which gathers all remaining arguments into an array.
Here's an example of how to use the spread operator to concatenate two arrays:
css
var numbers1 = [1, 2, 3];
var numbers2 = [4, 5, 6];
var combined = [...numbers1, ...numbers2];
console.log(combined); // prints [1, 2, 3, 4, 5, 6]
The ...numbers1 and ...numbers2 syntax is the spread operator, which spreads the contents of the arrays into a new array.
No comments:
Post a Comment