0

ES6 NEWBY

I'm new to es6 and I have a problem with the arrow function that I wasn't able to resolve or find anywhere.

Here's my problem, let's take this function as a reference:

Javascript:

const plus = function() {
    let sum = 0;
    for (let i = arguments.length - 1; i >= 0; i--) {
        sum += arguments[i];
        console.log(i);
    }
    return sum;
    console.log(arguments);
}

console.log(plus(2,4,6,8));

It works fine, the result is gonna be 20, and the browser is able to interpret it. The only problem is that when I try to translate in es6, the function will return an error, in this case, arguments is not defined:

const plus = () => {
    let sum = 0;
    for (let i = arguments.length - 1; i >= 0; i--) {
        sum += arguments[i];
        console.log(i);
    }
    return sum;
    console.log(arguments);
}

console.log(plus(2,4,6,8));

I get that part, but even if I define arguments as an empty array, the result will be still the same.

I'm trying to understand the error, but not like how to solve it, the theory behind to better use es6.

Thanks

Porcellino80
  • 447
  • 7
  • 32
  • 2
    An arrow function doesn't get an `arguments` object. You can use explicit spread syntax to capture the actual arguments in an array. – Pointy Dec 03 '19 at 14:12
  • 1
    Also [the MDN documentation explains this and other important differences.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Pointy Dec 03 '19 at 14:13

1 Answers1

1

Use the Spread_syntax :

const plus = (...arguments) => {
  let sum = 0;
  for (let i = arguments.length - 1; i >= 0; i--) {
    sum += arguments[i];
    // console.log(i);
  }
  // console.log(arguments);
  return sum;
}

console.log(plus(2, 4, 6, 8));
Taki
  • 17,320
  • 4
  • 26
  • 47