writingsabout

A

AZRULAZIZ

JavaScript Developer

JavaScript Scope Simplified

11 July, 2019

A quick and simple definition of scope in JavaScript:

Scope is a rule that determines where a variable can be found and how it can be used.


Scope & Lexical Environment

Lexical environment plays a big part in determining a function scope and its outer environment.

Lexical environment basically means the place where the code physically sits inside the code. Its about where the code is written and what surrounds it.


Consider this:

function a() {
    let num = 1;
    b()
}

function b() {
    console.log(num) // 0
}

let num = 0;
a()

What will happen when b is invoked? It returns 0 as value. This is because b sits on the global scope. It does not have any other outer environment. So it goes straight to global to look for a variable that does not exist within its own scope.


The outer environment of a function depends on where the functions sits lexically or in other word, where it is physically written.

Lets see an example:

function a() {
    let name = 'lily';

    function b() {
        console.log(name) // lily
    }

    b()
}

let name = 'zahra';
a()

Here b sits physically inside a. When b try to log the variable name, it doesnt found it in its own scope so it will refer to its lexical outer environment which is a. There it will found the variable name and use that instead.


Scope & Execution Context

Another way to think about scope is by looking at which execution context created or initialized the function. In the code above, b does not exist before the execution context for a starts. In contrast, a was created in the global execution context. The execution context determines where a function was created thus it automatically becomes that function's outer environment.


Block Scope

Block scope only applies when a variable is declared using let or const. Whenever a variable is declared inside a pair of curly braces, it will create a new scope for that variable.

let num = 2;
if (true) {
    let num = 1;
    console.log(num) // 1
}
console.log(num) // 2

In the code above, there are two variable defined with the same name but both holds different values. This is possible with block scoping only if we use let or const. If we use var instead, the first variable will be overwritten:

var num = 2;
if (true) {
    var num = 1;
    console.log(num) // 1
}
console.log(num) // 1

In essence, a variable can be on the global scope, function scope or the block scope. It is all determined by where it is created or where it physically sits.