Arrow Function vs Regular Function in JavaScript: Key Differences
arrow functions have a shorter syntax and do not have their own this context, inheriting it from the surrounding code. Regular functions have their own this and can be used as constructors, unlike arrow functions.Quick Comparison
This table summarizes the main differences between arrow functions and regular functions in JavaScript.
| Feature | Arrow Function | Regular Function |
|---|---|---|
| Syntax | Shorter, uses => | Longer, uses function keyword |
this Binding | Lexical (inherits from surrounding) | Dynamic (depends on call site) |
| Can be used as constructor | No | Yes |
| Arguments object | No own arguments | Has own arguments |
| Methods in objects | Not suitable as methods | Suitable as methods |
Usage with new | Throws error | Works |
Key Differences
Arrow functions use a concise syntax with the => symbol and do not have their own this context. Instead, they inherit this from the surrounding code where they are defined, which makes them useful for callbacks where you want to keep the outer this.
Regular functions declared with the function keyword have their own this context that depends on how they are called. This means this can change dynamically, which is useful in many object-oriented patterns but can also cause confusion.
Additionally, arrow functions cannot be used as constructors and do not have their own arguments object, while regular functions can be constructors and have their own arguments. This affects how you use them in different scenarios.
Code Comparison
const person = { name: 'Alice', regularFunction: function() { console.log('Hello, ' + this.name); }, arrowFunction: () => { console.log('Hello, ' + this.name); } }; person.regularFunction(); person.arrowFunction();
Regular Function Equivalent
function add(a, b) { return a + b; } console.log(add(2, 3));
When to Use Which
Choose arrow functions when you want a shorter syntax and need to keep the this context from the surrounding code, such as in callbacks or array methods. They are great for simple functions and avoiding this confusion.
Choose regular functions when you need a function with its own this, want to use it as a constructor with new, or need access to the arguments object. They are better suited for object methods and more complex function behaviors.
Key Takeaways
this from their surrounding scope, regular functions have their own this.arguments object; regular functions do.this and arguments to behave.