Javascript Hoisting

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

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

Javascript Hoisting – Interview Questions

Q 1: What is hoisting?
Ans: JavaScript moves declarations to the top of the scope.
Q 2: Are variables hoisted?
Ans: Yes, but not initialized.
Q 3: Are functions hoisted?
Ans: Yes, fully hoisted.
Q 4: Does let support hoisting?
Ans: Yes, but in a temporal dead zone.
Q 5: Does const support hoisting?
Ans: Yes, but it cannot be accessed before the declaration.

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.