Search code examples
javascriptfunctionhoisting

JS: Why value of "x" variable is undefined?


Why is the x variable in the example below returning undefined rather than 25?

var x = 25;

(function() {
  console.log(x);
  var x = 10;
})();


Solution

  • This is common problem of hoisting in javascript.The code actually looks like this.The value is assigned after the console.log.

    The second undefined(if run on developer's tool) is because the function is not explicitly returning anything

    This is how Javascript actually executes your code due to var hoisting:

    var x = 25;
    
    (function() {
      var x;
      console.log(x);
      x = 10;
    })();