DEV Community

Azrul Aziz
Azrul Aziz

Posted on • Updated on

Scope

Scope and some other things that I always forgot what is it about so I decided to write it down and hopefully it sticks in my brain.

Scope one-liner definition:

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. 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()
Enter fullscreen mode Exit fullscreen mode

What will happen when b is invoked? It will log 0 as the value of num. 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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)