0
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?

shu
  • 234
  • 4
  • 15
  • 2
    The first code is simply the fact that `foo` is set before `fn()` is actually run. And yes, the second is due to hoisting. – Rhumborl Apr 11 '18 at 09:33
  • @Rhumborl So, in JavaScript, statement is run after expression? – shu Apr 11 '18 at 09:36
  • @shu In JavaScript, declarations affect the whole scope in which they occur, the variable scope doesn't start at the declaration. – Bergi Apr 11 '18 at 09:57

1 Answers1

1

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.

Mohit Mutha
  • 2,921
  • 14
  • 25