I was trying to see how Lexical Scoping work within Javascript, So I tried below example. In my first example I am calling Test() within Main() and as expected it is giving error "bar" is undefined, similarly in second example I am calling setTimeout within Main(), but as again(setTimeout) it is function how it is able to get value of bar as Javascript has lexical scoping not Dynamic.
I am confused on this!!!
//Example No 1 without using setTimeout()
function Main()
{
var bar = "Main";
Test();
}
function Test()
{
console.log(bar);
}
//Prints bar is undefined which is fine as it is Lexical Scoping and bar is
//fine as there is no bar varibale in Test() or Global Context
Main()
//Example 2 with setTimeout()
var bar = "outside";
function main() {
var bar = "Main";
setTimeout(function() {
console.log(bar);
}, 1000)
}
//Prints value of bar = "Main"
main();