Hoisting variables in JavaScript

后端 未结 5 1537
误落风尘
误落风尘 2020-12-06 20:50

I understand Hoisting of variables is done in Java Script. I am unable to get why it outputs as undefined

 do_something()
    {
    var foo = 2;    
    cons         


        
5条回答
  •  青春惊慌失措
    2020-12-06 21:57

    This is how the interpreter sees your code,

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

    So it is printing undefined. This is a basic of variable hoisting. Your declarations will be moved to the top, and your assignation will remain in the same place. And the case is different when you use let over var.

提交回复
热议问题