I wanted to try the following code while examining “rest parameter” in JS. the output of the code was printed as -105. But to me, the code output is supposed to be +95. Because 100-2 = 98, 98-3 = 95. Why did this happen? Waiting for your help.
const sum = (...args) => {
return args.reduce((a, b) => a - b, 0);
}
console.log(sum(100, 2, 3));
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.
When you start the args.reduce(), you set as your starting value zero (that’s the , 0) at the end of the reduce statement). Everything goes from there. The first go-round, a=0 and b=100, so 0-100 = -100. Second element, your accumulator (which will always be a in this function) a=-100 and b=2, so -100-2 = -102. And so on.