1/*Hoisting is JavaScript's default behavior of moving
2all declarations to the top of the current scope (script or function).
3Be carefull that only declaration gets hoisted NOT the initialitations*/
4
5var x = 5;
6alert("x is = "+x+". y is = "+y);//result => x is = 5. y is = undefined.
7var y = 7;
8
9/*
10note that the code doesn't produce the error "y is not defined" like
11it would if we would omit y. It executes but not in the way you would want.
12*/
13
1// Example 1
2// Only y is hoisted
3
4x = 1; // Initialize x, and if not already declared, declare it - but no hoisting as there is no var in the statement.
5console.log(x + " " + y); // '1 undefined'
6// This prints value of y as undefined as JavaScript only hoists declarations
7var y = 2; // Declare and Initialize y
8
9
10// Example 2
11// No hoisting, but since initialization also causes declaration (if not already declared), variables are available.
12
13a = 'Cran'; // Initialize a
14b = 'berry'; // Initialize b
15console.log(a + "" + b); // 'Cranberry'