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

1

7

As part of my learning JavaScript, I try to write code to demonstrate the concept I am learning; today I'm learning hoisted variables. Here is the code I wrote:

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);   

I expected the following results:

A: My name is undefined
1: I am undefined
2: I am happy
B: My name is Jim

However, when testing my code at WriteCodeOnline.com and in another sandbox, the first console.log displays A: My name is. I am using a Chrome browser, if that makes a difference.

So, my question is, why does the hoisted local variable within the function return undefined while the hoisted global variable returns a blank?

Sevastopol answered 30/12, 2014 at 22:23 Comment(1)
It does appear that another question exists that answers my question. Had I known the answer to my question, I probably would have been able to find the other question as well. I have no problem if this question is closed.Sevastopol
O
7

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();
Overweary answered 30/12, 2014 at 22:26 Comment(5)
Well, it's good to know my expectations were right. Now back to learning that keywords, etc. can't be used as variable names.Sevastopol
@Sevastopol The important takeaway here is to keep your identifiers out of the global scope. :)Overweary
@RobG Don't you mean "name" in window?Grisons
@RobG console.log(typeof name); console.log("name" in window); prints out string true. The standards creators don't tend to leave creation of standard window properties up to the user.Overweary
@JLRishe—perhaps that's why it's an empty string until a user sets it to some other value.Troll

© 2022 - 2024 — McMap. All rights reserved.