console.log(d, 1); // undefined 1
var d = 8;
(function() {
console.log(d, 2); // undefined 2
var d = 10
console.log(d, 3); // 10 3
})();
console.log(d, 4); // 8 4
Could anyone please explain how this code produce the commented output ?
Important things to remember
Any variable declared with
var, will beundefinedbefore the control reaches the line where it is defined, unless something else is assigned. This is because, in JavaScript, declarations are hoisted.Any variable declared with
var, will be scoped to the function in which it is defined.With this understanding, lets look at the code.
First section
You access
dbefore the line in which theddeclared is executed. So,dwill beundefined.Mid section
Same thing here. You access
dbefore and after thedis actually declared. That is why you are gettingundefinedand10respectively.Last section
Since the variables declared within the functions will not be available outside the functions, in this line
dwill be the same variable declared at line 2. And the last assigned value is 8.