Variable rise in javascript

I am reading something on Variable Hoistingwhich I cannot figure out exactly how to learn it. I read the W3C school for an explanation. But, based on the sample code, I could not do what rises.

code 1 [This is the code from w3c school]

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

    <script>
    var x = 5; // Initialize x
    var y;     // Declare y

    elem = document.getElementById("demo"); // Find an element 
    elem.innerHTML = x + " " + y;           // Display x and y

    y = 7;     // Assign 7 to y

    </script>
       </body>
    </html>

But the above code still displays 'undefined'for the variable y.

If I changed the code as follows, then it works fine. But this code below is ordinary, not different, to understand'hoisting'

<script>
var x = 5;  // Initialize x
var y;
y = 7;
elem = document.getElementById("demo"); // Find an element 
elem.innerHTML = x + " " + y;           // Display x and y
</script>

Any help on this to understand "Variable Rise"?

+4
source share
3 answers

, , , var , , . , :

function foo() {
    var a = 42;
}

function foo() {
    var a;
    a = 42;
}

function foo() {
    a = 42;
    var a;
}

function foo() {
    var a;
    a = 42;
    var a;
}

JavaScript, :

function foo() {
    var a;
    a = 42;
}

, , :

function foo() {
    a = 42;
    b = 67;

    snippet.log(a); // 42
    snippet.log(b); // 67

    var a;
}
foo();
snippet.log(typeof a); // undefined
snippet.log(typeof b); // number?!
snippet.log(b);        // 67?!
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script>
Hide result

b foo? foo :

a = 42;
b = 67;

a , . , , .

b, b - foo.

( ):

+7

Javascript Engine

  • ( ).
  • .

( ) - script . var - . , var, ​​ . - undefined

- script . .

-1

, Javascript , "var a", a .

"a = 10" "a" 10. , 10.

a=10;
console.log(a); // 10
var a;
console.log(a); // 10
Hide result

.

+2

Javascript var x = 21; 2 : var x; x = 21;.

Part var x;always rises to the beginning of the attached function. The part x = 21;remains in its original place.

The same thing happens with ads function () {}- this will be raised at the top of the application scope:

function pie () {
    return 21;
}

as well as var.

+1
source

All Articles