Javascript functions | Sololearn: Learn to code for FREE!


Javascript functions

Having hard time to understand why this shows undefined instead of 1. var foo = 1 var bar = function (){ console.log(foo) var foo = 2 } bar() My assumption was the global variable foo will be displayed but I was surprised and confused to see undefined as the output.

5/7/2021 12:08:14 PM

Alpha Diallo

7 Answers

New Answer


They call it "hoisting". When you declare variable with "var" keyword the javascript engine "hoists" that variable and assigns "undefined" to it before compilation. Though javascript isn't precompiling language but it does this some sort of precompilation process. For example consider next code: console.log('hello') console.log('world') console.log(foo) var foo = "greetings" The moment we run this script the "foo" is already sitting at global scope level but it's not assigned yet, thus it is actually "undefined". Then js goes line by line from top to bottom, so it logs 'hello' (foo is still undefined) then it logs 'world' (foo is still undefined) and then js sees 'var foo = "greetings"' and only now 'foo' becomes assigned to 'greetings'.


So in your case when you call function "bar", javascript engine sees "var foo = 2" assignment inside the function and "hoists" that variable and assigns "undefined" to it. And then console.log logs that "undefined" and not "1". Sorry for my bad English. Hope that helps.


This is because you redeclare a new variable `foo` inside your function, but at the top of your function, the variable was undefined


I thought the first 'foo' will be accessed since I'm calling the console.log on it before making the redeclaration


The hoisting make the function 'bar' look at the foo variable within it instead of which is outside.


var foo = 1 function bar(){ console.log(foo) foo = 2; } bar();


Fill in the blanks to produce code which takes text as input, assigns it to the name variable, and outputs it.