Why does my returned local JavaScript variable return undefined, but the returned global variable returns empty?

As part of my learning JavaScript, I am trying to write code to demonstrate the concept that I am learning; today I am studying the raised 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 on WriteCodeOnline.com and in another sandbox, the first console.log displays A: My name is . I use a Chrome browser if that matters.

So my question is, why does the restored local variable inside the function return undefined, and the hoisted global variable returns empty?

+7
javascript hoisting undefined
source share
1 answer

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

This is a predefined property on window , so your hoisted var name does not actually create a new variable. There is already one in the global area with this name and by default has an empty string value.

To observe the behavior you expected, 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(); 
+7
source share

All Articles