Why is my JavaScript hoisted local variable returning undefined but the hoisted global variable is returning blank? [duplicate]

What is happening here is that you are accessing window.name.

This is a predefined property on window, so your hoisted var name isn’t actually creating a new variable. There’s already one in the global scope with that name and by default, it has a blank string value.

To observe the behavior you were expecting, you can use a variable name other than name, or put your code inside a function:

function hoisting() {
  console.log("A: My name is " + name);   

  function happy() {
    console.log ("1: I am " + feeling);   
    var feeling = "happy";
    console.log ("2: I am " + feeling);   
  }
  happy(); 

  var name = "Jim";
  console.log("B: My name is " + name);   
}

hoisting();

Leave a Comment