Hoisting variables in JavaScript

后端 未结 5 1514
误落风尘
误落风尘 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:34

    Only the declaration is hoisted, any assignment to a variable always stays where its originally from.

    0 讨论(0)
  • 2020-12-06 21:54

    The second function outputs undefined because you set the variable after you called it. The code you wrote is synchronous which means its read by the interpreter line by line, executed in order. If you don't define the variable before calling it, the console outputs undefined.

    This article explains it in more detail.

    0 讨论(0)
  • 2020-12-06 21:55

    Only the declaration is hoisted. the assigned variables are not hoisted. So you are

    0 讨论(0)
  • 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.

    0 讨论(0)
  • Javascript only hoists declarations, not initializations.

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

    Here, x and y are declared before any code is executed, the assignments occur later. At the time "x = y" is evaluated, y exists so no ReferenceError is thrown and its value is 'undefined'. So, x is assigned the undefined value. Then, y is assigned a value of 'A'. Consequently, after the first line, x === undefined && y === 'A', hence the result.

    Variable Declaration

    0 讨论(0)
提交回复
热议问题