Syntax differences
Arrow functions are shorter and use an =>
symbol. Here’s how they look compared to regular functions:
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
With an arrow function, you can skip the return
keyword if you're returning a single expression. This makes arrow functions popular for shorter, simpler functions.
this
binding
In regular functions, this
refers to the object that calls the function. However, arrow functions don’t have their own this
context. Instead, they inherit this from the surrounding code where they’re defined.
Here's an example to show how this difference affects behavior:
const object = {
name: 'JavaScript',
regularFunction: function() {
console.log(this.name); // 'JavaScript'
},
arrowFunction: () => {
console.log(this.name); // undefined
}
};
obj.regularFunction(); // 'JavaScript'
obj.arrowFunction(); // undefined
This might be useful when you pass function to event listeners, take a look:
document.querySelector('button').addEventListener('click', function() {
console.log(this); // refers to the button element!
});
arguments
object
Regular functions have access to the arguments
object, which holds all arguments passed to the function. Arrow functions don't have this; they use rest parameters ...args
instead.
// regular function with arguments
function sum() {
return Array.from(arguments).reduce((a, b) => a + b);
}
// arrow function with rest parameters
const sum = (...args) => args.reduce((a, b) => a + b);
Usage in callbacks
Arrow functions can simplify your code, especially when dealing with things requiring callbaks - for example promises or array methods like .map() and .filter().
// using arrow functions in array methods
const numbers = [1, 2, 3];
const squares = numbers.map(number => number * n); // [1, 4, 9]
When to use arrow functions vs regular functions
In general, arrow functions work well for:
- Short, concise functions like in array methods or callbacks
- Situations where this should stay consistent, like in class methods or closures
Regular functions are useful when:
- You need a specific
this
binding, like in object methods or event listeners - You want to use the
arguments
object without defining rest parameters
Let's notice something interesting here. As you can see, the differences are quite subtle. In most of the cases, it won't matter which one you choose, unless your codebase make heavy usages of this
or arguments
(unlikely).
The bottom line is that just choose whichever you prefer, just be consistent across your project.
Top comments (1)
Do you agree with this approach?