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 explicitreturnif 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
| Feature | Arrow Function | Regular Function |
|---|---|---|
Own this | No, inherits from outer scope | Yes, dynamic based on call site |
| Can be used as constructor | No | Yes |
| Syntax | Concise with => | Traditional function keyword |
| Arguments object | No | Yes |
| Best use case | Short functions, lexical this | Methods, 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.