Arrow Functions/Lambda Expressions
A lambda expression (aka “arrow function”) is very similar to an anonymous function, and can then be invoked like any function (but there are subtle differences).
Why use arrow function notation? Because it removes the noise from code, making it easier to read and overall less code.
Here’s what a lambda expression looks like:
// lambda expression
(param1, param2) => {
// some code ...
}
This is similar to an anonymous function:
// anonymous function
function(param1, param2) {
// some code ...
}
All we did was remove word function and placed a => (called fat arrow) between the parameter list and the body.
If the body of the lambda expression is just a single expression, they can be simplified:
(param1, param2) => expr; // where `expr` is ANY valid expression
param1 => expr; // a single parameter does not need parenthesis
() => expr; // zero parameters need parenthesis
() => { // with a body
return expr; // equivalent to the previous example
};
The value of expr is the return value of the lambda.
Subtle Differences
Lambda expressions can have no this reference, while functions can. This is an important distinction.
const f1 = function (param) {
console.log("this", this);
console.log("param", param);
}
const f2 = (param) => {
console.log("this", this);
console.log("param", param);
}
// first param to `apply` is `this`, second param is an array of callee function parameters
f1.apply("THIS for f1", ["param-value-for-f1"]);
f2.apply("THIS for f2", ["param-value-for-f2"]);
The first apply call will produce what you expect, second one won’t (because arrow functions don’t have their own this binding).
Limitations
You cannot use arrow functions:
- With
this,super, or methods likecall(),apply(), orbind() - As constructors
These terms may be confusing now but you will learn them with time. The important part to know is that we aren’t completely getting rid of ES5 function notation because ES6 arrow functions can’t completely replace the old syntax.