Before you start reading this post I recommend you to read Variable Scoping and Hoisting in JavaScript . In this post we will take a look on Scope Chain in JavaScript.
Let us consider you have declare a variable globally as below,
var var1 = "I am Global"; var2 = "I am also global"; this.var3= "I am also global"
In above code variables are declared globally, in other words they are not declared inside any function. There are few important points about above variable declaration,
- Whenever you declare a variable globally, you create property of global object. So we can say var1 is property of global object.
- Since var1 is property of global object so it is not configurable. It cannot be deleted.
- We are creating var2 without var keyword. It is possible to declare variable without var, if we are not in strict mode.
- In JavaScript global object can be accessed via this keyword.
Any property of global object cannot be deleted. Others can be deleted. So let us consider below code,
var var1 = "I am Global"; var2 = "I am also global"; this.var3= "I am also global" console.log(delete var1); console.log(delete var2); console.log(delete var3);
As we disused earlier var1 is not configurable so it cannot be deleted whereas other variables can be deleted. You will get output as below,
Above concept was very important in understating Scope Chain in JavaScript. JavaScript variables has scope
- In function they are defined
- If defined globally then throughout the program.
Let us consider following code snippet,
var var1 = "hello"; function funct1() { var var2 = "hello function"; function funct2() { var var3 = "hello nested function"; } }
In JavaScript each function or chunk of code (for example if-else) has a scope chain. Scope chain can be seen as list of objects or objects connected to each other as chain and any variable defined inside that has a scope in that particular chain.
Objects in above code snippet can be viewed as following. Consider variable var2. JavaScript will first search var2 as property of funct2. If it does not find that then it will search var2 as property of object of funct2 and so on it keep searching unless it reach global object. If it does not find variable in global object then JavaScript throw ReferenceError.
Concept of Scope Chain is very useful in understating closure in JavaScript. I hope you find this post useful. Thanks for reading.
Leave a Reply