Hoisting - 39Hoisted39 JavaScript Variables

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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.

Answers

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#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.

https://developer.mozilla.org/en-US/docs/Glossary/Falsy https://developer.mozilla.org/en-US/docs/Glossary/Falsy

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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/29667199/hoisted-javascript-variables

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils