Arrow Functions
“Fat arrow functions,” commonly known just as “arrow functions,” provide a modern alternative syntax to the traditional function keyword.
The Syntax Evolution
There are now three main ways to define essentially the same mathematical logic:
// 1. Traditional function declaration
function add(x, y) {
return x + y;
}
// 2. Function expression assigned to a variable
const add = function(x, y) {
return x + y;
};
// 3. Arrow function syntax
const add = (x, y) => {
return x + y;
};
When to use Arrow Functions
Arrow functions are not just syntactic sugar; they behave differently than traditional functions in a few key ways:
- They are usually expressions: Arrow functions are almost always assigned to a variable (
constorlet) or passed anonymously. - Implicit Returns: If your arrow function is a single line, you can omit the curly braces and the
returnkeyword entirely:const add = (x, y) => x + y; - No
thisbinding: This is the most crucial difference. Arrow functions handle scoping in a fundamentally different way, making them the preferred choice for callbacks and nested functions (which we will cover next). - Constructors: Fat arrow functions cannot be used as constructors (with the
newkeyword).