JavaScript interview question

What is Hoisting in JavaScript?

Answer

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.

Hoisting allows functions to be safely used in code before they are declared.

Example 01: Function Hoisting

One of the advantages of hoisting is that it lets you use a function before you declare it in your code.

getName("Sadhika Sandal");

function getName(name) {
  console.log("Hello " + name);
}

Output:

Hello Sadhika Sandal

Example 02: Variable Hoisting

console.log(message); // output : undefined
var message = "The variable Has been hoisted";

The above code looks like as below to the interpreter,

var message;
console.log(message);
message = "The variable Has been hoisted";

Example 03: let and const hoisting

All declarations (function, var, let, const and class) are hoisted in JavaScript, while the var declarations are initialized with undefined, but let and const declarations remain uninitialized.

console.log(x);
let x = 10;

// Output: ReferenceError: x is not defined

They will only get initialized when their lexical binding (assignment) is evaluated during runtime by the JavaScript engine. This means we can't access the variable before the engine evaluates its value at the place it was declared in the source code. This is what we call Temporal Dead Zone, A time span between variable creation and its initialization where they can't be accessed.

Note: JavaScript only hoists declarations, not initialisation

More Technical Interview Topics