/*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.
*/
/*
Hoisting in JavaScript is a behavior in which a function
or a variable can be used before declaration
*/
// using test before declaring
console.log(test); // undefined
var test;
1)Before your javascript(.js) file run there is global execution context
that is created even file is empty.Two phase Creation phase and Execution Phase.
2)In creation phase GEC create global object and this.In browser global object
will be browser.Javascript engines allocate memory for function even before your
code run.
3)After creation phase,There is Execution phase.
sayHi() //hello
function sayHi(){
console.log("hello")
}
Javascript already know your function even before it is executed
because of hoisting as in creation phase it memorized all javascript function
declaration.
sayHi(); //error out because of sayHi is const varible not exact function.
const sayHi= function (){
console.log("hey")
}
hoistedVariable = 3;
console.log(hoistedVariable); // outputs 3 even when the variable is declared after it is initialized
var hoistedVariable;
// hoisting is as if your `function fun() {}` was located here.
fun(); // works.
function fun() {}
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x
// accessing class
const p = new Person(); // ReferenceError
// defining class
class Person {
constructor(name) {
this.name = name;
}
}
// 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'