Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour Difference For Arrow-Functions vs Functions In Javascript [duplicate]

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));
like image 758
Shankar Shastri Avatar asked Jun 18 '18 03:06

Shankar Shastri


People also ask

How does the arrow function differ from other functions?

Unlike regular functions, arrow functions do not have their own this . The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

What is the difference between arrow functions and regular JavaScript functions?

Regular functions created using function declarations or expressions are 'constructible' and 'callable'. Since regular functions are constructible, they can be called using the 'new' keyword. However, the arrow functions are only 'callable' and not constructible.

Are arrow functions faster than regular functions?

Arrow functions are (mostly) just "syntactic sugar" for conventional function declarations. There is no performance difference.

What is the advantage of arrow function in JavaScript?

There are two major benefits of using Arrow functions. One is that it's a shorter syntax and thus requires less code. The main benefit is that it removes the several pain points associated with the this operator.


1 Answers

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)

like image 83
Robby Cornelissen Avatar answered Sep 24 '22 10:09

Robby Cornelissen