JavaScript gives us two main ways to define functions: arrow functions and regular functions. Although they may look similar at first glance, there are some key differences that can impact how your code runs and how you structure it. Let's break down these differences so you can better understand when to use each type.
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.
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! });
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);
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]
In general, arrow functions work well for:
Regular functions are useful when:
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.
Do you agree with this approach?
The above is the detailed content of Arrow function vs regular function in JavaScript. Which one to use?. For more information, please follow other related articles on the PHP Chinese website!