3

I need to understand how the JavaScript engines in browsers read functions. Consider the code below:

var g = 5;
alert(g); //alerts 5

function haha() {
    alert(g); // alerts NOTHING. Why is this? Why not alert 5? var g = 45 hasn't yet occurred
    var g = 45;
    alert(g); // alerts 45
};

haha();
alert(g); // alerts 5. Because g = 45 is a local variable.

Fiddle

geoyws
  • 3,326
  • 3
  • 35
  • 47
  • Thanks for everything guys. Looks like this is hoisting and has NOTHING to do with conflicting global and local variables. On another note, somebody needs to rework ECMA's documentation to make it easier to understand. – geoyws Apr 09 '14 at 05:08

1 Answers1

5

The effect you're seeing where alert(g) in the haha function alerts undefined is from variable hoisting.

The haha function is actually executed as:

function haha() {
    var g;
    alert(g);
    g = 45;
    alert(g);
}

This is because variable and function definitions are hoisted to the top of their scope in JavaScript.

The effect can lead to some rather unintuitive behavior, such as what you're seeing. The simple solution is to always declare your variables and functions before any executing code so that the written code matches what's being executed.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367