Moving variables in JavaScript

I understand Variable Raising is done in Java Script. I can not understand why it is output as undefined

 do_something()
    {
    var foo = 2;    
    console.log(foo);   
    } do_something()  // it prints 2

 do_something()
     {        
     console.log(foo);  var foo = 2;  
     } do_something()  // it prints undefined

How javascript make the rise of the second function should also print 2 according to my understanding. Buy why it's not him

+4
source share
5 answers

Only the ad rises. assigned variables do not rise. So you

+1
source

This is how the interpreter sees your code,

do_something() {
 var foo;
 console.log(foo); // undefined
 foo = 2;
}

do_something();

So this is the seal undefined. This is the base value of the lift variable. Your ads will be moved to the top, and your appointment will remain in the same place. And the thing is different if you use letover var.

+4
source

Javascript , .

var x = y, y = 'A';
console.log(x + y); // undefinedA

x y , . "x = y" y, ReferenceError 'undefined'. , x undefined. y 'A'. , x === undefined && y === 'A', , .

+2

undefined, . , , , , . , undefined.

This article explains this in more detail.

0
source

Only a declaration is declared, any assignment to a variable always remains where it is originally.

0
source

All Articles