What is the Scope and Scope chain in JavaScript?

Do you ever observe that a few variables in JS can not be accessed in one zone but can be accessed in another?

This is something you will observe even in other programming languages too. So what is this and why does it happen?

You might be aware of the words “local scope” and “global scope,” aren’t you? These vivid scopes are the reasons for variable access at various stages of the program. So, in this article, I will let you know the most central concept of JavaScript, which is called scope and scope chain.

So, what is the scope?

In JavaScript, we have the option of using same-named variables globally and locally without causing any debugging issues. The reason behind this uninterrupted error during debugging is “SCOPE”. So we can define scope as the space where the variables have different scopes/lifetimes, which means there are a few variables which are only accessible in blocks, a few in functions, and a few globally. 

“The space in which variables and statements are available is considered scope.” It allows variables with the same name to exist without colliding, and it prohibits external scopes from getting access to internal scopes. That means, if a variable has once been declared, it can be accessed only within the same scope in which it has been declared and is not accessible outside that scope.

[Also Read, JavaScript Coding Interview Questions and Answers]

What if JS doesn’t have a scope and scope chain option?

Let us know the importance of scope in JavaScript.

Modifications should be avoided:

If any variable is declared globally, then there is a chance of being modified by various parts of the program, knowingly or unknowingly. So, when the variable is declared locally, or block-wise, the chance of unwanted modifications of the variable is eliminated. 

No naming issues:

The variables in JavaScript have the option to be updated and redeclared. So there is a chance of modifications and updations of the variables unintendedly. And when certain variables are declared with the same names, then naming collisions to take place. So, to avoid name collisions, the scope is widely recommended. 

Garbage Collection:

When we finish using a variable in a dynamic language like JavaScript, the data is automatically trashed. If we don’t have one, the compiler would not be able to determine when to collect trash until we have clear scope on where we may access specific variables. A clear scope of where variables can be accessible helps the compiler in garbage collection after each scope.

Various scopes in JavaScript:

  1. Global scope
  2. Local scope
  3. Block scope

[Also Read, Difference Between var, let, and const in JavaScript]

Global Scope:

Global variables and global scope are variables declared outside of functions or blocks, that is, outside of the curly braces { }. These variables can be altered by any function or block. There is only one global scope, and it is considered the topmost scope. 

Functional Scope:

The variables that are declared inside the functions are considered local variables, which have function scope and can only be accessed by that function and its nested functions. 

Block Scope:

In JavaScript, the introduction of “let” and “const” makes the variables block scoped. That is when any variable is declared with let and const in ‘if’ or ‘for’ loops, those variables can only be accessed in those blocks. Just like function scope, block scope exists for blocks only.

Nesting of scopes in JavaScript:

Do you know that JavaScript has a nested scope that is called the inner scope and outer scope? So, a variable can be defined in a nested function or nested block and can easily be accessed within the nested function. 

An inner scope refers to a scope that is enclosed within another scope. The outer scope is the scope that surrounds another scope. So basically, we can say that the inner function is a child function which has an inner scope, while the outer function is the parent function which has an outer scope.

The inner scope can directly access the variables in the outer scope when there are nested scopes. These variables, however, are not available outside of the scopes. As a result, the inner functions or block variables are not accessible from the outside scope.

// Outer Function
function calcAge(birthYear){
    const name = 'Naveen';
    const currentYear = 2022;
    const age = currentYear - birthYear;
    // Inner Block
    if (age <= 60){
        console.log(`${name} is still employeed.`)
    }
    // Inner Function
    function yearsToRetire(){
        const retirement = 60 - age;
        console.log(`${name} will be retired in ${retirement} years.`)
    }
    yearsToRetire();
}
calcAge(1994);

Another Example

const role = 'JS Developer';

function getRole(){
    console.log(role);
}

function getRoleAgain(){
    const role = 'Random Value'
    getRole();
}

getRoleAgain();

// Output: JS Developer

Lexical scope

One of the interesting parts of JavaScript is lexical scope. This might seem tricky to understand at first, but once you learn it, it’s super easy to understand. So what do you mean by lexical scope? And how does lexical scope help JavaScript?

Lexical scope is the area where the variables are defined. If the variable is defined in a global area, then the variable’s lexical scope is the global scope, and if the same variable is defined in a function area, then its lexical scope is the function scope. 

An organised method to access variables in functions, blocks, and code in JavaScript is done through “LEXICAL SCOPE”. Through the lexical scope, the variable is defined from the area where it is defined, not from the area where it is invoked. 

Let us look at an example for a better understanding.

const role = 'JS Developer';

function getRole(){
    return role;
}

From the above example, let’s understand what the scope of the variable “role” is by simply answering the queries.

  • Where does the variable “role” define itself? the variable role, as defined in the global area.
  • Where does the variable “role” get invoked? the variable role is invoked in the functional area of “getRole”.
  • So, as per the definition of lexical scope, what would the scope of the variable “role” be? According to the definition of lexical scope, the scope of any variable would be the scope where it was first actually defined. So the scope of the variable “role” is the global scope since it was defined in a global area. 

I hope you get to know how the variable scopes are classified. Similarly, if the variable is defined within the function getRole, then the scope of the variable is function scope. 

function getEmpName(){
    const empName = 'John';
    return empName;
}

function empPosition(){
    const position = 'JS Developer';
    const info = `${empName} is a ${position}`
    return info;
}

console.log(empPosition())

// Output: Uncaught ReferenceError: empName is not defined

In lexical scope, the variable is accessed only with the parent and child functions or blocks. So, here in the above example, you might have noticed that the “empName” isn’t accessed in other functions as “empName” isn’t called by its parent or child function. 

Okay, now wrap up the concept of lexical scope in brief:

  1. The lexical scope of a variable is the place where the variable is being defined, not the place where it is invoked.
  2. Lexical scope is also called “static scope”.
  3. In general, variables are addressed during compilation rather than during runtime.
  4. The variables are invoked only in the child root of the parent root.

JS scope chain:

The scope chain in JavaScript refers to how the JS engine finds the variable in an organised and systematic manner. That is, first the JS finds the variable in the inner functional loop; if it isn’t found, then it looks in the outer functional loop. If even after the variable is not found in the outer loop, then it throws a “reference error” and this process is known as a variable lookup in JavaScript.

Summarise:

Okay, let’s summarise everything we have discussed in the article:

  1. JavaScript allows three types of scope, namely: global scope, local scope, and block scope.
  2. “Global scope” is the top scope where the variables are declared in the global area. 
  3. Local scope is also known as functional scope, where the variable is declared in functions.
  4. The block scope of the variable is when the variable is declared in blocks, that is, in if or for loops of the Javascript.
  5. The nested loop of the Javascript is known for the variable’s ability to access it from the inner and outer loops.
  6. This nested loop is the function of the JS engine to loop up for the variables according to the block, local, and global scopes. 

The lexical scope of the variable referred to the variable’s birthplace, not the place where it was brought up. That is the variable’s defined area, not the invoked area.

0 Shares:
You May Also Like