What does this extra 0 do?

This code works:

const sum = (x, y, z) => {
  const args = [x, y, z];
  return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6

This code does the same thing:

const sum = (x, y, z) => {
  const args = [x, y, z];
  return args.reduce((a, b) => a + b);
}
console.log(sum(1, 2, 3)); // 6

The difference is that I removed “, 0” in the second arrow function.

Why was the ‘, 0’ included in the original code?
I feel like there must be something that I’m missing in this. Is the 0 a default value?

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.

Note: Backticks are not single quotes.

markdown_Forums

I suggest reading up on the .reduce():

In this case, 0 is the initial value.

1 Like

Thanks. I’ll do that.