Skip to content

29 Lexical Scope

Biswajit Sundara edited this page Aug 18, 2023 · 1 revision

A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.

This will work fine

const person = {
    name: "Amar",
    cars: ["ferari", "limbo"],

    toString: function () {
        console.log(`${this.name} has car ${this.cars}`);
    }
}
person.toString();

This will not work. It will loose the context for name as this is referring to the new inner function

const person = {
    name: "Amar",
    cars: ["ferari", "limbo"],

    toString: function()  {
        this.cars.forEach( function(car)  {
            console.log(`${this.name} has car ${car}`);
        });
    }
}
person.toString();

To make it work, we need to use bind

const person = {
    name: "Amar",
    cars: ["ferari", "limbo"],

    toString: function()  {
        this.cars.forEach( function(car)  {
            console.log(`${this.name} has car ${car}`);
        }.bind(this));
    }
}
person.toString();

Lets use ES6 arrow function.

//don't use arrow function in toString() it will loose the context for `this` and throw error
const person = {
    name: "Amar",
    cars: ["ferari", "limbo"],

    toString: function()  {
        this.cars.forEach(car => {
            console.log(`${this.name} has car ${car}`);
        });
    }
}
person.toString();

Clone this wiki locally