diff --git a/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/02_lexical_scoping.js b/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/02_lexical_scoping.js new file mode 100644 index 0000000..145b8de --- /dev/null +++ b/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/02_lexical_scoping.js @@ -0,0 +1,21 @@ +const globalVar = "I am Global" + +function outer(){ + const outerVar = "I am Outer" + + + function inner(){ + const innerVar = "I am Inner" + + console.log(globalVar); // I am Global + console.log(outerVar); // I am Outer + console.log(innerVar); // I am Inner + } + + inner() +} + +outer() + +// In this eg, inner function can access globalVar and outerVar because they are within it's lexical scope. +// Inner function inherit the scope of the parent function where they are defined. \ No newline at end of file diff --git a/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/03_scope_chain.js b/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/03_scope_chain.js new file mode 100644 index 0000000..c09aefa --- /dev/null +++ b/03 - Chai aur Javascript/16 - Lexical Scoping and Closures/03_scope_chain.js @@ -0,0 +1,22 @@ +// Scope Chain + +function firstFunction(){ + const firstVar = "I am First" + + function secondFunction(){ + const secondVar = "I am Second" + + function thirdFunction(){ + const thirdVar = "I am Third" + + console.log(firstVar); // I am first + console.log(secondVar); // I am Second + console.log(thirdVar); // I am Third + } + thirdFunction() + } + secondFunction() +} +firstFunction() + +// In this example, thirdFunction can access firstVar and secondVar through the scope chain because of lexical scoping. \ No newline at end of file