Javascript Hoisting is a mechanism that moves all variable and function declarations to the top of their scope before code execution. However, variable assignments still happen where they originally were.
Note:- variable declaration is hoisted while the assignment remains in the same place.
console.log(emp_name);
var emp_name = "John";
Output:-
undefined
Note:- undefined means value is not defined in the variable.
Hoisting Process of above code
Now, the javascript hoisting mechanism run the above code into 3 steps
step1:- firstly declare emp_name variable
var emp_name
step2:- Now run the console.log
console.log(emp_name);
step3:- Now defined the emp_name value
emp_name = "John";
Complete hoisting process of the above code
var emp_name
console.log(emp_name);
emp_name = "John";
Output:-
undefined
call the variable after defined the value
var emp_name; // → Hoisted variable declaration
console.log(emp_name); // → undefined
emp_name = "John"; // → variable assignment remains in the same place
console.log(emp_name); // → John
Output:-
undefined
John
John
Hoisting Rule does not work when used ‘use strict’ before the code
'use strict';
console.log(emp_name);
emp_name = 'John';
Output:-
Uncaught ReferenceError: emp_name is not defined
Javascript Hoisting Rule for function
function declarations are hoisted to the top of their scope.
display_name();
function display_name() {
var emp_name='John'
console.log('Hello '+emp_name);
}
Output:-
Hello John
Hosting process of the function of the above code
function display_name() {
var emp_name='John'
console.log('Hello '+emp_name);
}
display_name();
Javascript Hoisting Rule does not work for function expression
display_name();
var display_name= function() {
var emp_name='John'
console.log(emp_name);
}
Output:-
Uncaught TypeError: display_name is not a function