Understanding Scope in Javascript

Photo by RetroSupply on Unsplash

Understanding Scope in Javascript

·

4 min read

Scope in js

If you'd like to code in JavaScript, understanding the scope of variables is a must.

So before understaning what is scope lets see some code snippets and examples so that we can understand scope in a better way

const a=1;
console.log(a);  // 1

so in the above code snippet we have declared a variable a which points to the value 1 and we displayed the value of a in the console , since a was declared before using it in the console.log(a) statement we were able to display the value in the console.

lets see another snippet to better understand the topic

if(true){
const a =1;
console.log(a);
}
console.log(a); // ReferenceError: a is not defined

here we have moved the declaration of a inside the if block ,even though we have declared the the variable a before using a why do we get this reference error?. lets explore to find out why this happens

The if block creates a scope for a and it is accesible only inside the if block

Now, let's put down a general definition of scope:

The scope is a policy that manages the accessibility of variables.

In simple words :

Scope tells us about where to look for things and where they can be accessed in the code

Javasript organizes scopes with functions and blocks ,Now lets see what is function scope and block scope in detail

Fucntion scope

A fuctions scope describes the variables availabe for use inside the function for use.

The code inside the function has access to :

  1. The functions arguments
  2. variables declared inside the function
  3. variables from its parent functions scope
  4. Global variables

Let's look at another code snippet to understand what was explained above

const myName='surya';
function introduceMyself(){
 const you='reader';
    function introduce(){
       const myProfession='software developer'
       console.log(`Hey ${you},I am ${myName} and I am a ${myProfession}`)
    }
  introduce();
}
introduceMyself(); //Hey reader,I am surya and I am a software developer

code explanation

Lets see how this code works first introduceMyself() is called and it sees that introduce() is invoked inside the function now it sees the console.log and it has use three varables namely you ,myName ,myProfession since the function has access to The local variable myProfession , variable you which is in the parent functions scope and the global variable myName we were able to sucessfully execute the code

Scope Chain

Whenever your code attempts to access a variable during a function call, the JavaScript interpreter looks for the variable in the local scope of the function if it is not availble in the local scope it moves up to search for it in the parent fuctions scope and the search will continue looking up until it reaches the global scope and this is called scope chain

Let's now revisit the concepts from the beginning of this section, and visualize the entire process

Untitled (2).png

Variable shadowing

what happens when you create a varable with the same name as somother varable in the scope chain

Consider the following example:

const symbol = '¥';

function displayPrice(price) {
  const symbol = '$';
  console.log(symbol + price);
}

displayPrice('80');//$80

In the above code snippet note that the variable symbol is declared in two places :

     1) Outside the function as a *global variable*

     2) insisde the function as a *local variable*

After invoking displayPrice()and passing it an argument of '80', the function outputs '$80' to the console.

How does the Javascript compiler know which symbol to use?

as discussed earlier in the scope chain section the javascript compiler first looks at the functions local scope first and moves on to search in the outer scope ,as the variable symbol is available in the local scope we get the output in console as $80

If there are any overlaps in variable names in different scopes the javascript compiler resolves it by moving from inner scope to outer scope and in this way any local variable declared with the same name as global variable takes precedence over the global variable and the local variable is used.

Lets Visually understand the order in which Js engine looks for varibles. scope-order.png

Summary

When a function is run, it creates its own scope. A function's scope is the set of variables available for use within that function. The scope of a function includes:

  1. The function's arguments.
  2. Local variables declared within the function.
  3. Variables from its parent function's scope.
  4. Global variables.

When it comes to accessing variables, the JavaScript engine will traverse the scope chain, first looking at the innermost level (e.g., a function's local variables), then to outer scopes, eventually reaching the global scope if necessary.

some useful resources

dmitripavlutin's blog

mdn scope

lets connetct twitter