JavaScript Interview Question #21

How does this behave differently in arrow functions and regular functions?

JavaScript Fundamentals, Types, Scope & Functions Junior Beginner

Quick Interview Answer

A regular function's this value generally depends on how the function is called. An arrow function does not define its own this; instead, it captures this lexically from the surrounding scope.

Detailed Explanation

A regular function's this value generally depends on how the function is called. An arrow function does not define its own this; instead, it captures this lexically from the surrounding scope.

This distinction is particularly useful in object methods that start callbacks. An arrow callback can retain the method's surrounding this, while an ordinary callback may receive a different this unless it is explicitly bound.

Code Example

const user = {
    name: "Asif",
    regularMethod() {
        const showName = () => {
            console.log(this.name);
        };

        showName();
    }
};

user.regularMethod(); // Asif