hoisting javascript code example

Example 1: js hoisting

/*Hoisting is JavaScript's default behavior of moving 
all declarations to the top of the current scope (script or function).
Be carefull that only declaration gets hoisted NOT the initialitations*/

var x = 5;
alert("x is  = "+x+". y is = "+y);//result => x is = 5. y is = undefined.
var y = 7;

/*
note that the code doesn't produce the error "y is not defined" like
it would if we would omit y. It executes but not in the way you would want.
*/

Example 2: function hoisting in js

console.log(functionBelow("Hello"));
function functionBelow(greet) {
   return `${greet} world`;
}
console.log(functionBelow("Hi"));

Example 3: Hoisting in JavaScript MDN

// Example 1 
// Only y is hoisted

x = 1; // Initialize x, and if not already declared, declare it - but no hoisting as there is no var in the statement.
console.log(x + " " + y); // '1 undefined'
// This prints value of y as undefined as JavaScript only hoists declarations
var y = 2; // Declare and Initialize y


// Example 2 
// No hoisting, but since initialization also causes declaration (if not already declared), variables are available.

a = 'Cran'; // Initialize a
b = 'berry'; // Initialize b
console.log(a + "" + b); // 'Cranberry'

Example 4: function hoisting in js

console.log(functionBelow("Hello"));
var functionBelow = function(greet) {
   return `${greet} world`;
}
console.log(functionBelow("Hi"));