Explain the concept of "hoisting" in JavaScript

Answer:

Hoisting in JavaScript is a behavior in which variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that you can use variables and functions before they are declared in the code, though their initialization is not hoisted.s

Key Details:

  1. Function Declarations:
greet();
function greet() {
  console.log('Hello, World!');
}

This works because the greet function is hoisted to the top.

  1. Variable Declarations:
console.log(a); // undefined
var a = 10;

Here, a is hoisted and initialized with undefined.

console.log(b); // ReferenceError
let b = 10;
  1. Class Declarations:
const instance = new MyClass(); // ReferenceError
class MyClass {}

Key Points:

MDN Web Docs: Hoisting