+ 3

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.

7th May 2021, 12:08 PM
Alpha Diallo
Alpha Diallo - avatar
8 ответов
+ 3
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'.
8th May 2021, 12:06 AM
Artur
Artur - avatar
+ 2
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.
8th May 2021, 12:14 AM
Artur
Artur - avatar
+ 1
I thought the first 'foo' will be accessed since I'm calling the console.log on it before making the redeclaration
7th May 2021, 2:28 PM
Alpha Diallo
Alpha Diallo - avatar
+ 1
The hoisting make the function 'bar' look at the foo variable within it instead of which is outside.
8th May 2021, 8:47 AM
Alpha Diallo
Alpha Diallo - avatar
0
var foo = 1 function bar(){ console.log(foo) foo = 2; } bar();
7th May 2021, 12:12 PM
Kurakula Govardhan
Kurakula Govardhan - avatar
0
Fill in the blanks to produce code which takes text as input, assigns it to the name variable, and outputs it.
1st Jun 2021, 3:39 PM
اورد عبدالامير جاسم _المرحلة الثانية شعبة[ A]
اورد عبدالامير جاسم _المرحلة الثانية شعبة[ A] - avatar
0
Var foo = 1 function bar(){ } console.log(foo) foo=2 bar();
11th Jun 2022, 1:52 AM
justin wright
justin wright - avatar