I came across this piece of code from a friend and I'm wondering why is this working this way.
Assume two files: scope2.js and scope3.js
scope2.js
console.log(foo);
var foo=6;
woo=5;
(function()
{
console.log(foo);
console.log(woo);
var foo=5;
console.log(foo);
console.log(woo);
})();
The output when executed in NodeJS env, >>> "node scope2.js"
undefined undefined 5 5 5
Now, Scope3.js
console.log(foo);
var foo=6;
woo=5;
(function()
{
console.log(foo);
console.log(woo);
var foo=5;
var woo=6;
console.log(foo);
console.log(woo);
})();
Output of the above code in nodejs env is :
undefined undefined undefined 5 6
Why this behavior ?
I understand most of the basics of variable scoping in JS, but this is confusing me, I dont want to understand something with some bad assumptions.