Search code examples
javascriptarrow-functions

Behaviour Difference For Arrow-Functions vs Functions In Javascript


I wanted to understand the behavior of a normal function vs arrow functions.

Arrow Function:

function arrowFunc() {
  return () => arguments
}


console.log(arrowFunc(1, 2, 3)(1))

Normal Function

function normalFunc() {
  return function() {
    return arguments
  }
}

console.log(normalFunc(1, 2, 3)(1))

Both the results are expected to be same, but looks like arrowFunc defined above considers the first arg list, where as the normalFunc considers the second set of arg list.

Also tried babel-compilation to understand the difference, but looks like the behavior is different as shown below:

Babel Output:

"use strict";

function arrowFunc() {
  var _arguments = arguments;

  return function() {
    return _arguments;
  };
}

console.log(arrowFunc(1, 2, 3)(1));

function normalFunc() {
  return function() {
    return arguments;
  };
}

console.log(normalFunc(1, 2, 3)(1));


Solution

  • Both the results are expected to be same

    No, they're not.


    From the first line of the MDN page on arrow functions (emphasis mine):

    An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.

    And further down the same page:

    Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the arguments of the enclosing scope [...]

    And in the ECMAScript specification:

    NOTE: Arrow functions never have an arguments objects. (sic)