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?
javascript hoisting undefined
Jimlockwood
source share