Before diving deeper, let’s take a moment to establish the difference between two popular terms that are often improperly interchanged by beginner developers — declaration and initialization.
x = 5;
x = 7; // Assign 7 to x
var x; // Declare x
console.log(x); // => 7
Simple enough? Well, hoisting isn’t as consistent as you’d expect at first.
var z = 3;
console.log(z); // => undefined
var z = 4;
Undefined? But before! Wha! Huh?
Now you see why this can be confusing and promote creating simple errors unconsciously! But don’t worry, we can easily work around this.
The moral of the story (pre-ES2015, another article coming soon) is to just keep things simple by declaring all variables at the top.