Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Initializing variable in function

Tags:

javascript

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

like image 236
Daniel Avatar asked Dec 29 '22 01:12

Daniel


1 Answers

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.

like image 86
lonesomeday Avatar answered Jan 07 '23 04:01

lonesomeday