Scope chain

Each execution context has a link to its outside world or a link to its parent depends on where the function sits.

// Global variable
var x = "x";

function findName(){
 var b = "b";
 return printName();
function printName() {
 var c = "c";
 return "Me";
function sayMyName() {
 var a = "a";
 return findName();

All of these functions are going to be able to access the variable the global variable x.

function findName can not access variable c and a.

function printName can not access variable b and a.

function sayName can not access variable b and c.

All the functions have their own variable environment. They have access to each their own variables but they also have little link what we call a scope chain. The scope chain links and gives us access to variables that are in our parent environment.

In JavaScript our lexical scope where function was defined determines our available variables.

  • Not where the function is called (dynamic scope)

The idea of lexical scope which is also called static scope in a language means that only by looking at the source code we can determine which environment the variables in data are available. That is what the compiler does the JavaScript compiler looks at the code and attaches all these scope chain. Even before runs the code.

Scope Chain

Variables declared outside a function in what we call global scope and they can accessed in any other scope that inside of functions.

Leave a Reply

Your email address will not be published.