Skip to main content

Functions and Closures

Arrow Functions and Lexical This

0:00
LearnStep 1/3

Modern Function Syntax and Scope

Arrow functions, introduced in ES6, provide a more concise syntax for writing function expressions. They are particularly useful for short, one-line functions and callbacks.

1. Basic Syntax and Implicit Returns

If the function body contains a single expression, you can omit the curly braces {} and the return keyword. This is called an implicit return.

javascript

2. Lexical 'this'

The most significant feature of arrow functions is how they handle the this keyword. Unlike regular functions, which define their own this based on how they are called, arrow functions capture 'this' from their surrounding lexical context. This solves common issues with callbacks in classes or object methods.

javascript

3. When NOT to use Arrow Functions

Because they lack their own this binding and cannot be used as constructors, avoid them for:

  • Object methods: If you need to access the object via this.
  • Constructors: They cannot be called with new.
  • Event handlers: If you need this to refer to the DOM element triggering the event.
javascript