spread vs rest syntax in JS, a little confused.
What is the difference between the rest and spread operator?
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.
C# 12 spread operator in practice
Hi all,
I'm currently having some issues learning the spread vs rest operator in JS. In the beginning of the lecture, the teacher said that the spread operator is on the right side of the "=" whereas the rest operator is on the left side of the "=". I thought I had understood it as it made sense with the problems that was presented. Then towards the end of the lecture when he used it as a function, he was able to use the rest operator on the RIGHT side of the function. Why is that?
const add = function (...numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) sum += numbers[i];
console.log(numbers);
};
add(2, 3);Shouldn't this then be a spread operation instead of a rest operation since the ... is on the right side of the =? Or is it because when the function gets called, since the input is individual numbers, it will automatically do the opposite of what it currently is? like since its already individual numbers, the ... essentially will use it as a rest operator whereas if maybe I put in an array then it will understand to use it as a spread operator?
please ELI5, the more I look at it the more I confuse myself
thanks