Javascript

Understanding scope in JavaScript


JavaScript is a simple, partially easy to use language with broad attractions in the web development industry.

Unfortunately, it is built upon a complex collection of language mechanics which without careful study will not be understood even by seasoned developers. It is even harder to learn JavaScript completely.

In this article, we will focus on one of the core concepts of the language known as scope which tends to be very tricky and often challenging to understand. In order to have a deep understanding of the language, we shouldn’t be fulfilled when once something just works rather we should be keen to know why and how it works.

At the end of this article, we will gain a solid understanding of the inner workings of scope in JavaScript as I will practically unveil the underneath working of the JavaScript engine.

What is scope?

If you ask an automobile sales consultant for a car model that is not in her car store,  she will not be able to sell it to you because she only has access to the cars in her store’s inventory. So you will have to look out for another store till you find it.

In software development, this concept is termed scope. The scope is a collection of stored variables as well as the rules for accessing these variables by name at any time.

Working principles of the javascript engine

Let’s see how the engine process this statement var age = 5; . The first thing the compiler does is to break the statement down into tokens. But during code generation, when the compiler encounter var age it ask the current scope if the variable age already exists if so the compiler will ignore the declaration and move on. Otherwise, it will declare a new variable called age for the current scope.

The compiler will further produce a new code for the engine to execute. age = 5 is handled by the engine during the execution phase.

In the execution phase, the engine asks the scope if the variable age exists, and can be accessed. If so, the engine assigns the value of 5 to it. Otherwise, it looks outside the current scope till variable age is accessed but if variable age doesn’t exist, the engine will throw a ReferenceError meaning hey dude I have searched even till the global scope yet I can’t find the variable age.

Understanding JavaScript scope

Before we dive deep into the practical understanding of scope, it will be best to explain some commonly used terms in this article.

  1. Engine: it takes charge of the compilation and execution of our JavaScript program.
  2. Compiler: it handles the work of parsing(splitting a program or other input into pieces of data that can be easily stored or manipulated) and code generation.
  3. Lexing: this entails the breakdown of a statement into tokens. For instance, let’s consider the statement var age = 5; the engine breaks it down to var, age, =, 5 and the comma.

I will mimic the JavaScript engine and scope conversations a lot so that you can easily understand the concept of scope. Considering the piece of code, let’s see how the engine handles scope.

function car ( carName ) {
       function carModel ( model ) {
          
          console.log (`The model of this ${ carName } car is ${ model } `) ;
          function yearOfManufacture ( year ) {
                    
            console.log(`This ${ carName } car model is ${ model } and was manufactured in ${ year }` );
          }
          yearOfManufacture ( 1992 );
       }
       carModel ( "Carmry Le") ;
    }
    car ( "Toyota" ) ;

I will use the code snippet above to :

  1. Demystify the JavaScript engine’s thoughts.
  2. Explain the nested scope.

Demystify the JavaScript engine’s thoughts

Taking a look at the code snippet above, there are three visible scope and one imaginary ( global ) scope. The javascript engine executes the console.log(...) statement in the yearOfManufacture function scope and then move from the current scope to the outer scope looking for the three variables.

It wouldn’t find the variable carName in the yearOfManufacture function scope so it’ll move to the carModel function scope, still, it doesn’t find it so it will move to the carName function scope where it will find it. This is the same with other variables.

Nested scope

Just as a function can be nested, the scope can also be nested inside other scopes so if a variable cannot be found in the current scope, the engine will check out the immediate outer scope till it is found. The global scope is the final checkpoint ie.

if the engine search for a variable up to the global scope and it is not found it gets upset and throws a ReferenceError to the console. The same variable names can be used in multiple layers of a nested scope. When this happens, the inner variable shadows the outer variables ( shadowing ). Regardless of shadowing, scope look up start with the innermost scope being executed and it works upwards till the first match is found then stops.

Block scope

This entails the declaration of variables as local as possible and as close as possible to where it will be used. This concept is usually seen in loops, conditionals, with ( now obsolete ), try and catch.

In block scope, the scope that is created in the object only exists in the lifetime of the conditionals, loops, try and catch statement and not in the surrounding scope. I think a code snippet will explain better.

for (let count = 0; count < 5; count++) { 
        console.log( count );  // 0,1,2,3,4
    }
    console.log( count );     // uncaught ReferenceError

Lexical Scope

Lexical scope is a scope that is created by the developer when writing the code. This based on the developer’s human perception of the program as he sees it before compilation by the engine.

Conclusion

Understanding scope in JavaScript could be quite challenging to some developers, so I have tried my best to get everyone along especially the beginner JavaScript developers by illustrating with easy to understand terms and vocabulary. I hope this piece gave you an easy understanding of scope in JavaScript. If you have any challenge, feel free to ask in the comments below.


Share on social media

//