Scope chaining  in JavaScript

Scope chaining in JavaScript

ยท

4 min read

Scope and Scope Chain are fundamental concepts of JavaScript and other programming languages. Yet, these concepts confuse many new JavaScript developers. The knowledge of these concepts is essential in mastering JavaScript.

Without further ado, let's get started ๐Ÿ˜Š

What is the scope?

I have written a complete blog on scope just before this blog kindly check it out, here I will explain shortly.

The scope can be defined as the space in which variables and statements are accessible.

In Javascript we have three types of scope:

  • Global scope
  • Function/local scope
  • Block scope.

Let's learn what those are:

Global scope

  • The default scope
  • There is only one global scope in the program
  • It is the top scope that englobes the entire code
  • The declarations inside this space can be accessed anywhere in the code

Local scope or Function scope

  • Created by a function invocation
  • The declarations inside the function are only accessible there

Block scope

  • The space between a pair of curly braces (if block, for block, etc.)
  • Applicable to let and const
  • Declarations are only accessible inside the block.

Scope Chain

The scope chain is how Javascript looks for variables. When looking for variables through the nested scope, the inner scope first looks at its own scope. If the variable is not assigned locally, which is inside the inner function or block scope, then JavaScript will look at the outer scope of said function or block to find the variable. If Javascript could not find the variable in any of the outer scopes on the chain, it will throw a reference error.

In simple words

The Scope Chain is the hierarchy of scopes that will be searched in order to find a function or variable.

Let's take an example and go through this process step by step. Check the below code.

const language = 'English'
const name = 'chhakuli'

function displayIntroduction() {
  const name = 'sami'
  const country = 'India'

  function displayInfo() {
    const name = 'samiksha'
    console.log(`My name is ${name}, I'm from ${country} and I speak ${language}`)
  }

  return displayInfo()
}

displayIntroduction()

Before we dive into how, let me briefly talk about the **execution context**.This concept won't be covered in this article(I have complete blog on execution context you can check it out) but it is important to explain what it is in order to make it easier to understand scope chain. So, execution context is an environment in which javascript code is evaluated and executed. When the code first starts running it creates a global execution context and a function execution context is created on each function invocation. The scope chain of this code looks similar to this:

Global execution context.png

Each execution context has a scope chain. It consists of the variables and objects referenceable by the execution context. Besides the variables and objects it has a property called outer that stores the reference to the parent's scope chain.

When the displayInfo function is executed and reaches name it searches for it in the local scope chain, finding samiksha as the value. The same process happens for country but it is not in the local scope.

So, how is javascript able to reference it?

When the constant is not found in the local scope javascript reaches to the parent's local memory accessible by the reference stored in outer, getting India as the value.

Last but not least, the same thing happens to language in this case the javascript engine goes all the way up the scope chain reaching the global scope to find the constant, retrieving the value English. It is important to know that the scope chain works only one way, from the inner scope to the outer scopes, making it impossible for the global execution context to have access to country, for example.

Also know that since the global execution context is the top context the outer points to null, so if the variable wasn't there it would be implicitly declared, if not in strict mode, or an error would be returned.

Conclusion

Scope and scope chain are fundamental topics to understand how the javascript engine process and executes code.

To recap:

  • There are three types of scope: global scope, function scope and block scope
  • Scopes make possible to have variables with the same name without colliding with each other
  • Variables and objects in inner scopes are not accessible from outer scopes

So this is how the scope chain works. If one scope needs to use a certain variable but cannot find it in the scope, it will look up in the scope chain and check whether it can find a variable on one of the outer scopes. If the variable is available in the outer scope, then the child scope has the access to it. If it is not there in any outer scopes, the JavaScript will throw a reference error. So this process is called variable lookup.

Thanks for reading :)

Did you find this article valuable?

Support Chhakuli Zingare by becoming a sponsor. Any amount is appreciated!

ย