Hoisting

 Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that regardless of where variables and functions are declared within a scope, they are accessible throughout that entire scope.

Hoisting applies to both variable declarations (var, let, and const) and function declarations. However, it's important to note that only the declarations are hoisted, not the initializations.

Here's how hoisting works for variables declared with var:

console.log(x); // Output: undefined var x = 5; console.log(x); // Output: 5

  1. During the compilation phase, the variable declaration var x; is hoisted to the top of its containing scope.
  2. At runtime, the assignment x = 5; occurs as usual.
  3. When console.log(x); is executed, x exists in the scope, but it hasn't been assigned a value yet, so it logs undefined.

However, hoisting works differently for variables declared with let and const. Unlike var, variables declared with let and const are hoisted to the top of their containing block, but they are not initialized until the actual declaration statement is reached in the code. This means you cannot access them before the line where they are declared, which helps prevent some common coding errors.

Function declarations are also hoisted in JavaScript:

foo(); // Output: "Hello, world!" function foo() { console.log("Hello, world!"); }

In the above example, the function declaration function foo() { ... } is hoisted to the top of its containing scope during compilation, allowing the foo() function to be invoked before its actual declaration in the code.

Comments

Popular posts from this blog

Transform values with a stream

Collections Framework

Inspect a collection