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";
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";
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
John
Hoisting Rule does not work when used ‘use strict’ before the code
'use strict';
console.log(emp_name);
emp_name = 'John';
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);
}
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);
}
Javascript Hoisting – Interview Questions
Q 1: What is hoisting?
Q 2: Are variables hoisted?
Q 3: Are functions hoisted?
Q 4: Does let support hoisting?
Q 5: Does const support hoisting?
Javascript Hoisting – Objective Questions (MCQs)
Q1. JavaScript hoisting moves declarations to the ______.
Q2. Which keyword supports hoisting?
Q3. Are let variables hoisted?
Q4. Hoisting occurs during which phase?
Q5. Function declarations are ______ hoisted.