All about Scope in JavaScript

All about Scope in JavaScript

·

4 min read

Breaking down the Scope mystery in mind, we come to the question of why we need it and what exactly it is. So, let's take the process from the very beginning and understand a few basic terms as pre-requisite. State - A place where we can store, later modify, and retrieve the variables. Quite simple right? But where do these operations in the state happen? Having variables in our program gives rise to an important question regarding the existence of these variables, and how our program accesses these certain variables when needed. Here is now, Scope comes into the picture.

There is a pre-defined set of rules which answers all these questions which is aka the Scope.

💡
Javascript is primarily interpreted language, which means that it doesn't require a separate step for compilation before execution. In this article, we will break it down to the compilation step and the execution step and understand the concept of scope with these perspectives.

In general, for compilation, the compiler does three steps. We won't dig that deep into these steps, but knowing what they do won't hurt.

  • Tokenizing/Lexing (Breaking up a string of characters into meaningful chunks)

  • Parsing (Taking the array of tokens and turning it into a nested tree)

  • Code generation (Processing of the parsed tree and converting it into executable code)

//Example of a variable declaration
let a = 10;

The engine will see this line of code in two perspectives. First, where the compiler will handle the compilation. Second, where the engine handles the execution.

During the compilation phase, this line will be broken into smaller chunks, for eg ( |const| a | = | 10 |; | ) and parsed as a nested tree. Pay more attention now, as now is the crazy part. In the next step, the code generation step, it is quite common to presume that the compiler allocates the memory to the variable "a" by putting the value "10" in it.

But the truth is, Encountering var a, the compiler first asks the Scope to see/ask/check if this declaration already exists or not. If exists, it ignores this declaration and does not exist, it asks the Scope to declare a new variable assigning "a" in the Scope collection. Code produced by the compiler is then executed where the assignment operation takes place. Now in this step, the engine asks the Scope if this declared identifier(let a) exists in the current scope (or in simple words, is accessible). If so, the engine uses this let, if not it looks somewhere else. If the engine eventually can find this declaration, it assigns the value of "10", if not yells out a ReferenceError.

(I know there are too many if's used, but pull your hair and try to understand this amazing concept)

Okay, let me write in short also, the Compiler declares a variable ( if not found previously declared in the current scope) and the engine while executing look-ups for the variable in the scope, assigns a value (if found).

So finally we come to a more specific definition of our main lead here, The compiled code, when used by the engine for execution look-ups for the declaration and this look-up is consulting Scope.

This is quite sufficient but if you are finding this interesting and want to dig only a little more, here it is. There are two types of look-ups our Engine friend uses -

  • LHS look-up (Left Hand Side)- Look-up to the left side of the assignment operation. Mainly trying to find the variable container or the reference to it)

  • RHS look-up (Right Hand Side) - Look-up associated with the right side of the assignment or can be said a Value-retrieval look-up.

      function logA(a){ 
        console.log(a);
      }
    
      logA(22);
    
      /* In the first line of code, our engine performs RHS look up for finding 
      the logA declaration.
      In the parameter, encountering a, engine asks for the LHS reference which 
      the scope identifies as a parameter.
      While logging through console.log(a), engine uses RHS look up for the value
      retrieval of a.
      */
    

I hope I was able to clearly explain the concept of Scope. It used to confuse me often, but the key is to read and practice it repeatedly until you understand it.