SA
메인 내용으로 이동

JavaScript Arrow Functions vs JavaScript Functions

When to Use Each

Use traditional functions

  • When you need to use function hoisting (arrow functions are not hoisted).
  • If you need to access the arguments object.
  • When using methods that will be added to an object's prototype.
  • If you need a dynamic context (this), such as in event handlers.

Use arrow functions

  • For shorter syntax in functional programming scenarios.
  • When working with higher-order functions that expect a function callback.
  • In cases where you want to retain the lexical this scope (e.g., in nested functions or event handlers).
  • For single-line functions with implicit returns.

Differences

Syntax

Arrow functions provide a shorter syntax. They are written with an arrow rather than the function keyword.

Traditional function

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

Arrow function:

const add = (a, b) => a + b;

this Binding

One of the most significant differences is how this is handled. In traditional functions, this is dynamic and can change depending on the context in which the function is called. In arrow functions, this is lexically scoped, meaning it uses this from the surrounding code where the function is defined.

No Binding of arguments

Arrow functions do not have their own arguments object. Instead, they access the arguments object of the closest non-arrow parent function.

Cannot be used as Constructors

Arrow functions cannot be used as constructor functions. They cannot be called with new.

No Duplicate Named Parameters

Traditional functions allow duplicate named parameters in non-strict mode, while arrow functions do not, regardless of strict mode.

No prototype Property

Arrow functions do not have a prototype property.

Implicit Return

In arrow functions, if you have a single expression, you can omit the curly braces {} and the return statement. The expression automatically returns its result.