spread vs rest syntax in JS, a little confused.
What is the difference between the rest and spread operator?
Spread Operator vs Rest Parameter
Rest and Spread operator: Three dots that changed JavaScript
I wouldn't recommend naming the function parameter of a reduce previous.
function sum(...args) {
return args.reduce((previous, current)=> {
return previous + current;
});
}
The first parameter is the accumulator. total or previousTotal or anything that suggests that we're building on it may be better.
previous suggests that we're comparing to the previous item in the array, and examples that use it can make reduce functions even more complicated to understand than they need to be.
What is the rest operator in JavaScript?
The rest operator (…) collects all remaining elements into an array. It is often used in function arguments.
Example:
function sum(…numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
Learn more in our JavaScript rest and spread free course video.
Are rest and spread operators supported in all JavaScript environments?
They are supported in modern browsers and environments with ES6 support. Use Babel or a transpiler for older browsers. Learn more in the JavaScript rest and spread free course video.
How is the spread operator different from the rest operator?
The spread operator (…) expands elements of an array or object, while the rest operator collects multiple elements into a single array. Discover their differences in the JS rest and spread with free video tutorial.