Javascript scope chain and the lexical environment

Javascript scope chain and the lexical environment

Introduction

Welcome to my next post of the Javascript Interview series. This series is about clearing the javascript interview questions with main topics explained in detail with examples. You can check my blog on hoisting before moving forward in the series

In this blog I will cover-

  • what is a scope?

  • what is the lexical environment and scope chain.

Let's first understand what is scope in javascript?

In JavaScript, scope determines where the variables are present, it can be inside the function or in the global space.

Now let's see a Sherlock and Watson example to understand scope chain and lexical environment.

function sherlock(){
  console.log(name);
}

function watson(){

  var name = 'doctor';
  sherlock();

}

var name = 'detective';
watson();

so In this example, the output will be, detective , How do I get the result and whether it checked the scope of the execution context let's visualize!!

For understanding this you must know how global execution context is created and how scope works, You can check this article for better understanding, freecodecamp.org/news/javascript-execution-..

1.Now when we execute the code a global execution context is created always when this is equal to the window object and two function execution context for sherlock and watson will be created.

Lex1.png

  1. The name will be given a value of detective in the global execution phase.

lex2.png

  1. Now it will encounter the function invocation Watson() and a new execution context will be created for watson, and the name will be declared undefined.

lex3.png

  1. It will now assign the value 'doctor' to the variable name,

lex4.png

  1. Inside the execution context of watson, it will encounter the function invocation for sherlock and will create a new execution context for sherlock.

Now the question lies where is sherlock lexically present?

So the answer is, sherlock is created by global execution context even though it was invoked in watson execution context, Here you can say that sherlock is lexically present in the global execution context.

As sherlock does not have a variable name declared inside it it will look in the global execution context for name, and hence our answer is detective, not undefined and doctor.

lex5.png

The process of looking for a variable in a lexical environment is together called a scope chain.

I hope you find this article useful and share it with someone who has an interview. I will write more blogs in this series keep reading!