Concise Syntax
Arrow functions are a shorter syntax for function expressions.
They are great for small callbacks and inline logic.
JavaScript Tutorial
Arrow functions provide a shorter syntax for function expressions.
They are especially useful for callbacks and inline logic.
Concise code improves readability, and lexical this avoids common bugs in callbacks.
Knowing their limitations helps you choose the right function style.
(params) => expression
(params) => { ... }const add = (a, b) => a + b;
console.log(add(2, 3));Simple one-line function with implicit return.
const square = n => n * n;
console.log(square(5));Parentheses are optional for a single parameter.
Arrow functions are a shorter syntax for function expressions.
They are great for small callbacks and inline logic.
Arrow functions do not have their own this.
They inherit this from the surrounding scope, which is useful in callbacks.
Single-expression arrow functions can return without the return keyword.
Use parentheses when returning an object literal.
const makeUser = (name) => ({ name });
console.log(makeUser("Ava"));Wrap object literals in parentheses.
const team = {
name: "Alpha",
members: ["A", "B"],
list() {
return this.members.map((m) => this.name + "-" + m);
}
};
console.log(team.list());Arrow functions keep this from the outer scope.
Without
const add = function(a, b) {
return a + b;
};With
const add = (a, b) => a + b;Arrow functions should not be used as object methods when you need this.
Wrap object literals in parentheses.
Use regular functions when readability is better.
Arrow functions inherit this from the outer scope.
No, they do not have a prototype and cannot be used with new.
When you need a method with its own this value.
Practice: Convert a function expression into an arrow function.
const multiply = function(a, b) {
return a * b;
};
// TODO: convert to arrow
One Possible Solution
const multiply = (a, b) => a * b;
console.log(multiply(3, 4));No, they inherit this from the surrounding scope.
No, they cannot be used with new.
For short callbacks and when you want lexical this.
Try using arrow functions in different callbacks.