A somewhat basic question here. I can see what is going on but I can't really understand why it would work this way.
a = false;
var k = function() {
console.log(a);
var a = true
console.log(a);
}();
I would expect the log to read "false, then true" but "a" undefined at first. Can someone please elaborate why it does this.
Ps. I'm not looking for an answer telling me what I should do, I'm looking for an explanation of the inner workings of this piece of JavaScript.
Thanks in advance
This is because Javascript scoping works by something called "hoisting". When a parser reads a Javascript function, it goes through and finds all the variables defined in that scope (using the var
) keyword (remember that the only type of scope in Javascript is the function scope). It then puts them at the top of the function.
So the parser interprets your code as follows:
a = false;
var k = (function() {
var a;
console.log(a);
a = true
console.log(a);
}());
(NB I have corrected your function call so that it doesn't return a syntax error.)
Obviously this now sets a
to undefined
before it does the first console.log
.
As the MDC docs say:
Every definition of a variable is really a declaration of the variable at the top of its scope and an assignment at the place where the definition is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With