Skip to main content

Arrow Functions

JavaScript arrow functions are a very useful tool to learn and master. Here’s a complete introduction to everything you need to know.

Syntax Evolution

Let’s refactor a regular function step by step to understand arrow function syntax:

Step 1: Regular Function Declaration

Step 2: Function Expression

Step 3: Arrow Function with Braces

Step 4: Remove Parentheses (Single Parameter)

Step 5: Implicit Return

For single-parameter arrow functions with a single expression, you can omit parentheses, braces, and the return keyword.

Syntax Variations

No Parameters

Multiple Parameters

Returning Objects

Wrap object literals in parentheses:

Multiple Statements

Execution Context (this)

The main difference between arrow functions and regular functions is execution context (i.e. the value of this). Technically speaking, most other differences often mentioned either stem from this one or are side effects of it.

Regular Functions: Dynamic this

In a regular function, this is dynamic and depends on how the function was invoked:

Arrow Functions: Lexical this

Arrow functions, unlike regular ones, don’t define their own execution context. Therefore this inside an arrow function always refers to the lexical this (i.e. the scope in which the arrow function was defined).
Arrow functions cannot be used as constructors and will throw a TypeError when used with the new keyword.

When to Use Arrow Functions

✅ Good Use Cases

Array Methods

Callbacks

Preserving Context

❌ Avoid Arrow Functions For

Object Methods

Event Handlers Needing this

Constructors

Advanced Patterns

Immediately Invoked Arrow Functions

Curried Functions

Async Arrow Functions

Summary

  • More concise than regular functions
  • Implicit returns for single expressions
  • No need for function keyword
  • Lexical this (inherits from parent scope)
  • Cannot be used as constructors
  • Perfect for callbacks and array methods
  • Use for short callbacks and array methods
  • Avoid for object methods and event handlers
  • Great for preserving this context
  • Use regular functions when you need dynamic this