Arrow Functions &
Lexical this
Master modern JavaScript's concise function syntax and understand how arrow functions inherit this from their surrounding scope.
What is a Function?
A function is a reusable block of code that performs a specific task. In JavaScript, functions are first-class citizens: they can be stored in variables, passed as arguments, and returned from other functions.
// Traditional function declaration function greet(name) { return "Hello, " + name; } // Function expression (stored in a variable) const greetAsExpression = function(name) { return "Hello, " + name; };
Enter the Arrow Function
Arrow functions use the => syntax to create shorter, more concise functions. They were introduced in ES6 (2015) and are now the most common way to write functions in modern JavaScript.
// Traditional const add = function(a, b) { return a + b; }; // Arrow function const add = (a, b) => a + b;
Arrow Syntax Variations
() => valueUse empty parentheses
x => x * 2Parentheses optional
(a, b) => a + bParentheses required
// Multi-line body: use braces + return const calculate = (x, y) => { const sum = x + y; return sum * 2; };
What is this?
In JavaScript, this is a special keyword that refers to the context in which a function is called. It changes depending on how the function is invoked, not where it is written.
The this Problem
With regular functions, this is determined by how the function is called, not where it's defined. This creates a classic bug when using callbacks inside objects:
const timer = { seconds: 0, start: function() { setInterval(function() { this.seconds++; // Bug! "this" is window, not timer console.log(this.seconds); // NaN }, 1000); } };
Lexical this: The Core Rule
The Fix with Arrow Functions
Replace the regular callback with an arrow function, and this automatically refers to the enclosing object:
const timer = { seconds: 0, start: function() { setInterval(() => { this.seconds++; // ✓ "this" is timer console.log(this.seconds); // 1, 2, 3... }, 1000); } };
Regular vs Arrow: Key Differences
| Regular Function | Arrow Function | |
|---|---|---|
| Syntax | function(x) { ... } |
(x) => { ... } |
this binding |
Dynamic (caller) | Lexical (definition) |
arguments |
Has its own | Inherits from parent |
| As constructor | ✓ Can use new |
✕ Cannot use new |
| Hoisting | Declarations hoisted | Not hoisted |
| Best for | Methods, constructors | Callbacks, inline logic |
How to Choose the Right Function
this correctly refers to the object.this from the method..map(), .filter()).arguments or new? Use a regular function: arrow functions lack both.Example: Arrow Functions with Arrays
Arrow functions shine with array methods like .map(), .filter(), and .reduce():
const numbers = [1, 2, 3, 4, 5]; // Double each number const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10] // Keep only even numbers const evens = numbers.filter(n => n % 2 === 0); // [2, 4] // Sum all numbers const sum = numbers.reduce((acc, n) => acc + n, 0); // 15
Example: Lexical this in Practice
const team = { name: "JavaScript Squad", members: ["Alice", "Bob", "Charlie"], introduce: function() { return this.members.map(member => { return `${member} is on ${this.name}`; }); } }; team.introduce(); // ["Alice is on JavaScript Squad", // "Bob is on JavaScript Squad", // "Charlie is on JavaScript Squad"]
Example: Event Handlers
A common real-world pattern: using arrow functions inside class methods for event handlers.
class Counter { constructor() { this.count = 0; this.btn = document.querySelector("#btn"); // ✓ Arrow preserves "this" as the Counter instance this.btn.addEventListener("click", () => { this.count++; console.log(this.count); // 1, 2, 3... }); } }
Common Mistakes to Avoid
this to be the global scope, not the object.{} but omitting return silently returns undefined.() => {key: val} is parsed as a block, not an object. Wrap in parentheses: () => ({key: val})// ✕ Wrong: arrow function as method const obj = { name: "Oops", greet: () => console.log(this.name) // undefined! }; // ✓ Correct: regular function as method const obj = { name: "Works", greet() { console.log(this.name); } // "Works" };
When to Use Which
| Scenario | Use Arrow | Use Regular |
|---|---|---|
| Array callbacks | ✓ .map(x => x*2) |
|
| Event handlers (in class) | ✓ preserves this |
|
| Promises / async | ✓ .then(r => r.json()) |
|
| Object methods | ✓ needs own this |
|
| Constructors | ✓ arrows can't be new |
|
| Prototype methods | ✓ needs dynamic this |
Question 1 of 5
What does "lexical this" mean in the context of arrow functions?
this from the enclosing scope at definition time, not call time. This is the core difference from regular functions.Question 2 of 5
const dog = {
name: "Rex",
bark: () => {
console.log(this.name + " says woof!");
}
};
dog.bark();
What will dog.bark() output?
bark is an arrow function, this is inherited from the enclosing scope (global/module scope), not the dog object. In modern JavaScript (strict mode), the global this is undefined, so accessing this.name throws a TypeError. In older, non-strict environments, this would be the window object, and this.name would likely be an empty string. This is the classic mistake of using arrow functions as object methods.Question 3 of 5
Which of the following is a valid arrow function that returns an object literal?
() => ({ key: value }). Without parentheses, the {} is interpreted as a function body block, not an object.Question 4 of 5
Which scenario is best suited for an arrow function?
.map(), .filter(), and .then(). They should not be used as object methods (A), constructors (C), or prototype methods (D) because those need their own this binding.Question 5 of 5
const app = {
data: [10, 20, 30],
double: function() {
return this.data.map(n => n * 2);
}
};
console.log(app.double());
What is the output of app.double()?
double is a regular function (so this = app), and the .map() callback is an arrow function (so it inherits this from double). The result is [20, 40, 60].