0
0
JavascriptComparisonBeginner · 4 min read

Arrow Function vs Regular Function in JavaScript: Key Differences

In JavaScript, 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.

FeatureArrow FunctionRegular Function
SyntaxShorter, uses =>Longer, uses function keyword
this BindingLexical (inherits from surrounding)Dynamic (depends on call site)
Can be used as constructorNoYes
Arguments objectNo own argumentsHas own arguments
Methods in objectsNot suitable as methodsSuitable as methods
Usage with newThrows errorWorks
⚖️

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

javascript
const person = {
  name: 'Alice',
  regularFunction: function() {
    console.log('Hello, ' + this.name);
  },
  arrowFunction: () => {
    console.log('Hello, ' + this.name);
  }
};

person.regularFunction();
person.arrowFunction();
Output
Hello, Alice Hello, undefined
↔️

Regular Function Equivalent

javascript
function add(a, b) {
  return a + b;
}

console.log(add(2, 3));
Output
5
🎯

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

Arrow functions inherit this from their surrounding scope, regular functions have their own this.
Arrow functions cannot be used as constructors; regular functions can.
Use arrow functions for concise syntax and callbacks, regular functions for methods and constructors.
Arrow functions do not have their own arguments object; regular functions do.
Choosing the right function type depends on how you want this and arguments to behave.