1

I was looking at:

https://babeljs.io/learn-es2015/

And it has the following example:

// Lexical arguments
function square() {
  let example = () => {
    let numbers = [];
    for (let number of arguments) {
      numbers.push(number * number);
    }

    return numbers;
  };

  return example();
}

square(2, 4, 7.5, 8, 11.5, 21); // returns: [4, 16, 56.25, 64, 132.25, 441]

and I was trying to understand what was really happening here: specifically can someone explain why does square use an internal arrow function instead of just performing the required actions? could this not be re-written to be:

function square() {
    let numbers = [];
    for (let number of arguments) {
      numbers.push(number * number);
    }

    return numbers;
}

What does the extra wrapping in "example" change in the behavior of this function?

epeleg
  • 10,347
  • 17
  • 101
  • 151
  • It's just a toy example and not meant to be useful (compare `square = (...nums) => nums.map(x => x*x);`). It just demonstrates [how `arguments` works inside an arrow function](https://stackoverflow.com/q/30935336/1048572). – Bergi Jan 12 '18 at 14:07

1 Answers1

1

It simply demonstrates that arguments in the arrow function refers to arguments of square function. this is not true with a simple function :

function square() {
  let example = function() {
    let numbers = [];
    for (let number of arguments) {
      numbers.push(number * number);
    }

    return numbers;
  };

  return example();
}

square(2, 4, 7.5, 8, 11.5, 21); // returns: []
Troopers
  • 5,127
  • 1
  • 37
  • 64
  • This is exactly right. `let example = () => { ... };` is ECMAScript6 for `let example = function () { ... };` Personally I don't find the new => construct to be a net benefit. Anything that decreases the readability of the code for no clear reason ought to be left out. – bearvarine Apr 05 '18 at 02:26
  • @bearvarine the benefit of the arrow function is to use `arguments` and `this` key words to refer to the parent function instead of the current function – Troopers Apr 05 '18 at 06:50