+ 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.
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'.
+ 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.
+ 1
I thought the first 'foo' will be accessed since I'm calling the console.log on it before making the redeclaration
+ 1
The hoisting make the function 'bar' look at the foo variable within it instead of which is outside.
0
var foo = 1
function bar(){
console.log(foo)
foo = 2;
}
bar();
0
Fill in the blanks to produce code which takes text as input, assigns it to the name variable, and outputs it.
0
Var foo = 1 function bar(){
} console.log(foo) foo=2 bar();