JavaScript: initializing a variable in a function

A few basic question here. I see what is happening, but I can’t understand why this will work.

a = false; var k = function() { console.log(a); var a = true console.log(a); }(); 

I would expect the log to read "false, then true" first, but "a" is undefined. Can someone refine why he does it.

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 JavaScript fragment.

Thank you in advance

+4
source share
1 answer

This is because the Javascript scope is working under the name of "climb". When the parser reads a Javascript function, it looks through and finds all the variables defined in this area (using the var keyword) (remember that the only kind of area in Javascript is the function area). He then places them at the beginning 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 fixed your function call so that it does not return a syntax error.)

Obviously, this now sets a to undefined before it makes the first console.log .


According to MDC :

Each definition of a variable is really a declaration of a variable at the top of its scope and an assignment at the place where that definition is.

+10
source

Source: https://habr.com/ru/post/1338999/


All Articles