Search code examples
javascriptvariableshoistinglexical-scope

Variable hoisting examples


Hi I have a snippet of code. I am confused about change of value x1 when I remove non-related part of same code. I searched about it and I came to know that it has to do with hoisting. But the value x1 is still unclear even with hoisting concept for me. Can someone please make me clear on this?

var x = 10;               
    
function main() {
  document.write("<br>x1 is " + x);
  x = 20;
  if (x > 0) {
    var x = 30;
    document.write("<br>x2 is " + x);
  }
  var x = 40;
  var f = function(x) { 
    document.write("<br>x3 is " + x); 
  }
  f(50);
}

main();

The output of this code is:

x1 is undefined
x2 is 30
x3 is 50

If I change this code to:

        
var x = 10;

function main() {
  document.write("<br>x1 is " + x);  
}

main();

The output is:

x1 is 10


Solution

  • All variable and function declarations get "hoisted" or moved to the top of their scope. The undefined value for x is caused because the var x statement gets moved up to the top of main however the assignment = 30 does not.

    So, your code will read more like this:

    var x = 10;                             // x is 10
    function main() {
        var x;                              // x declaration is "hoisted"
        document.write("<br>x1 is" + x);    // x1 is undefined
        x = 20;                             // x is 20
        if (x > 0) {
            x = 30;                         // x is 30
            document.write("<br>x2 is" + x);// x2 is 30
        }
        x = 40;                             // x is 40
        var f = function(x) {               // x is 50
            document.write("<br>x3 is" + x);// x3 is 50
        }
        f(50);
    }
    main();
    

    You can read more about Hoisting here: JavaScript Scoping and Hoisting