Reputation: 244
function fn() {
console.log(foo);
}
const foo = 3;
run();
How come this variable inside of a function can read a global variable that is even declared and assigned under the function statement?
How does JavaScript work in this scenario? I'd like to understand how it works.
fn();
function fn() {
console.log("hello");
}
I know this does work because of function hoisting. But the first code is another story, right?
Upvotes: 0
Views: 40
Reputation: 3001
JavaScript is interpreted. The function is evaluated only when you call it. If you move the function call to before the variable declaration it will not work. See the code below (it gives a error)
function fn() {
console.log(foo);
}
fn();
const foo = 3;
The function fn()
is only a declaration till the point it is called.
Upvotes: 1