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));
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.
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.
Arrow functions are (mostly) just "syntactic sugar" for conventional function declarations. There is no performance difference.
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.
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
, ornew.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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With