Author: Michal Szymanski
Free live lesson
In other words; a variable can be used before it has been declared.
Example 1 gives the same result as Example 2:
x = 5; // Assign 5 to x console.log(x); // Result 5 var x; // Declare x
var x; // Declare x x = 5; // Assign 5 to x console.log(x); // Result 5
To understand this, you have to understand the term "hoisting".
The let and const Keywords
Variables and constants declared with
const are not hoisted!
You will learn about
const in the next lessons.
Example 1 does not give the same result as Example 2:
var x = 5; // Initialize x var y = 7; // Initialize y console.log(x + " " + y) // Display x and y - Result 5 7
var x = 5; // Initialize x console.log(x + " " + y) // Display x and y - Result 5 undefined var y = 7; // Initialize y
Does it make sense that y is undefined in the last example?
This is because only the declaration (var y), not the initialization (=7) is hoisted to the top.
Because of hoisting, y has been declared before it is used, but because initializations are not hoisted, the value of y is undefined.
Example 2 is the same as writing:
var x = 5; // Initialize x var y; // Declare y console.log(x + " " + y) // Display x and y - Result 5 undefined y = 7; // Initialize - assign 7 to y
Declare Your Variables At the Top !
If a developer doesn't understand hoisting, programs may contain bugs (errors).
To avoid bugs, always declare all variables at the beginning of every scope.
Previous lesson Next lesson
Spread the word: