Skip to main content

Command Palette

Search for a command to run...

Learn scope and much more in Javascript with Aman...

Updated
โ€ข2 min read
Learn scope and much more in Javascript with Aman...

Hey Techies, This is Aman... Let's learn scope in javascript.

Scope (of a variable/function)

I will walk you through the simplest two points to understand the scope in JS.

  • Up to where in the program/script, the variable can be accessible.
  • Is the variable accessible inside any particular function?
var x=10;
function show()
{
var y=12;
console.log(x);
}
function show2(){
var z=34;
console.log(x)
}
{
  let a = 20;
  console.log(a);
}

show();
show2();

Output: Capture.JPG In the above snippet of code, we have four variables x, y, z, and a. All four variables have a different scope. Let us discuss their scopes.

  • Variable x: It has global scope, which means it is accessible anywhere in the program, be it any function body or if else block. It will be accessible in both show() and show2() functions.
  • Variable y and z: These variables have function scope. Since they are defined inside the function. They won't be accessible outside the function show and show2 respectively.

    var variable is global/function scoped.

  • Variable a: It has block scope, simply it is defined inside the block and cannot be accessed outside the block.

    let and const variable is block scoped.

Lexical Environment

Before explaining what is lexical environment, it is important to know where it gets placed. The lexical environment is present in every execution context, global or local.

The lexical environment is the local memory along with the lexical environment of its parent.

While accessing a variable, the javascript engine looks for it in the local scope, if it is not present then it checks the lexical environment of the parent. This check goes till the global scope.

diagram.png

Lexical Environment of global execution context points to null.

The chain of lexical environments is known as scope chaining.


Hope this helps you. Thank you for reading and let's connect! :) Aman Verma on Linkedin

A

Nicely Explained... well done Aman!