0
0
JavascriptHow-ToBeginner · 4 min read

How Does This Work in Arrow Function in JavaScript

In JavaScript, this inside an arrow function does not refer to its own context but inherits this from the surrounding (lexical) scope. Unlike regular functions, arrow functions do not have their own this, making them useful to avoid common this binding issues.
📐

Syntax

An arrow function uses a concise syntax with an arrow => between parameters and the function body. It does not have its own this binding and inherits it from the outer scope.

  • (parameters) => expression - returns the expression result
  • (parameters) => { statements } - block body with explicit return if needed
javascript
const arrowFunction = (param) => param * 2;
💻

Example

This example shows how this behaves differently in arrow functions compared to regular functions inside an object method.

javascript
const obj = {
  value: 42,
  regularFunction: function() {
    console.log('regularFunction this.value:', this.value);
  },
  arrowFunction: () => {
    console.log('arrowFunction this.value:', this.value);
  }
};

obj.regularFunction(); // 'this' refers to obj
obj.arrowFunction();   // 'this' refers to global or undefined in strict mode
Output
regularFunction this.value: 42 arrowFunction this.value: undefined
⚠️

Common Pitfalls

A common mistake is expecting this inside an arrow function to refer to the object it is defined in. Arrow functions inherit this from the outer scope, so inside object methods, this may not be what you expect.

Also, arrow functions cannot be used as constructors because they lack their own this.

javascript
const obj = {
  value: 10,
  wrongArrow: () => {
    console.log(this.value); // undefined, 'this' is not obj
  },
  correctRegular() {
    console.log(this.value); // 10
  }
};

obj.wrongArrow();
obj.correctRegular();
Output
undefined 10
📊

Quick Reference

FeatureArrow FunctionRegular Function
Own thisNo, inherits from outer scopeYes, dynamic based on call site
Can be used as constructorNoYes
SyntaxConcise with =>Traditional function keyword
Arguments objectNoYes
Best use caseShort functions, lexical thisMethods, constructors

Key Takeaways

Arrow functions inherit this from their surrounding scope instead of having their own.
Use arrow functions to avoid manual this binding in callbacks or nested functions.
Do not use arrow functions as object methods if you need this to refer to the object.
Arrow functions cannot be used as constructors because they lack their own this.
Regular functions have dynamic this based on how they are called.