JavaScript Interview Questions

23 Questions
JavaScript

JavaScript

Web DevelopmentFrontendBackend

Question 5

What is hoisting in JavaScript?

Answer:

Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means you can use functions and variables before they are declared in the code. However, while function declarations are fully hoisted, variable declarations are hoisted without their initializations. Understanding hoisting helps prevent unexpected behavior and bugs in your code.

Here is an example demonstrating hoisting:

console.log(hoistedVar); // undefined
var hoistedVar = 'This variable is hoisted';

hoistedFunction(); // 'This function is hoisted'

function hoistedFunction() {
    console.log('This function is hoisted');
}

In this example, hoistedVar is hoisted to the top of its scope but remains undefined until its assignment. The hoistedFunction is fully hoisted, allowing it to be called before its declaration.

Recent job openings