Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

hoisting - 'Hoisted' JavaScript Variables

I do not fully understand why the following displays "hoisted" towards the end.

var x = 'set';
var y = function () 
{
    // WHAT YOU DON'T SEE -> var x; 
    // is effectively "hoisted" to this line!

    if (!x) 
    { 
        // You might expect the variable to be populated at this point...it is not
        // though, so this block executes
        var x = 'hoisted'; 
    }

    alert(x); 
}

//... and this call causes an alert to display "hoisted"
y();

Any pointers would be appreciated.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Quoting MDN Docs on var hoisting,

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

So, in your case, JavaScript knows that a local variable (not the one declared outside) x is defined somewhere in the function, but it does not know the actual value of it until the execution reaches an assignment statement which assigns to x. (Declarations are processed during the compile time and assigments are done in the execution time) Till the assignment is done, the default value undefined will be used. Since undefined is falsy, the condition

if (!x) {

is satisfied and the assignment statement is executed. That is why you are getting hoisted in the alert box.


Let's say you have not declared x inside the function,

var x;

var y = function () {
    if (!x) {
        x = 'hoisted';
    }
    alert(x);
}

y();
alert(x);

Here, since x is not declared anywhere within the function, at runtime, JavaScript will look for x in the higher scopes. In this case, it finds it right outside the function. So, that x will be used. Since you assigned hoisted to x, the inner alert will also say hoisted and after leaving the function, alert(x) will also alert hoisted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...