Trivia Questions1 min readPremium

What is hoisting?

Demystifying Hoisting in JavaScript

Hoisting in JavaScript is a crucial concept that profoundly influences how variables and functions are declared, initialized, and scoped. Understanding hoisting is essential for every JavaScript developer to navigate the intricacies of the language and to write error-free, efficient code. MDN’s glossary entry on hoisting is a concise reference.

What is Hoisting?

Hoisting is JavaScript’s default behavior of moving declarations to the top of their scope before code execution. This mechanism allows functions and variables to be used before they are explicitly defined in the script, affecting how the execution context is established.

console.log(myVar); // Output: undefined
var myVar = 10;
console.log(myVar); // Output: 10

hoistedFunction(); // Output: "Function has been hoisted"
function hoistedFunction() {
  console.log("Function has been hoisted");
}

Understanding the Implications of Hoisting

While hoisting provides flexibility in how you structure your code, it also requires a thorough understanding to prevent common pitfalls, such as unintentionally using variables before they are defined, leading to undefined values.

ES6, let, and const

The introduction of let and const in ES6 brought changes to hoisting behavior. Unlike var, which is initialized with undefined, let and const are hoisted but not initialized, creating a temporal dead zone until their declaration is... premium content.

Premium

Keep reading with Premium

Get the rest of this guide plus every premium question, solution, and system design deep dive.

  • All premium solutions
  • System design deep dives
  • Company-specific prep

4.9/5 from our users