Concepts

Hoisting

Hoisting is a somewhat misunderstood behavior in JavaScript where declarations are conceptually moved to the top of their scope before the code is executed. It's important to distinguish between the behavior of different types of declarations to fully grasp this concepts:

Variable Declaration with "var"

The Picture: Imagine variables declared with var are physically hoisted to the top of their scope. Both the declaration and initialization are seemingly lifted.

Example:

console.log(myVar); // Outputs 'undefined', the variable exists, but hasn't been initialized  
var myVar = 10; 
console.log(foo); // 10

Implication: This can leed to confusion if you're accessing a var-declared variable before its initialization line. It exists, but the value is undefined.

"let" and "const" Declarations

Temporal Dead Zone (TDZ): Variables declared with let and const are also hoisted, but they are not initialized. Attempting to access them before their declaration line results in a ReferenceError.

Example:

console.log(myLet); // ReferenceError: myLet is not defined 
let myLet = 10;

Implications: let and const promote more predictable code behavior by disallowing access to uninitialized variables.

Function Declaration

Full Hoisting: Function declarations are fully hoisted - both the name and the function definition.

Example:

helloWorld(); // Outputs 'Hello World!'
 
function helloWorld() { 
  console.log('Hello World!');
}

Implications: You can invoke a function declaration even before it appears in your code's sequence.

Function Expression

Partial Hosting: Only the variable declaration is hoisted.

Example:

// Function Expression
console.log(bar); // undefined
bar(); // Uncaught TypeError: bar is not a function
var bar = function () {
  console.log('BARRRR');
};
console.log(bar); // [Function: bar]
 
// Function Declaration
console.log(foo); // [Function: foo]
foo(); // 'FOOOOO'
function foo() {
  console.log('FOOOOO');
}
console.log(foo); // [Function: foo]

Important Notes:

  • Class Declarations: Classes are not hoisted in a traditional sense. They exhibit a behavior similar to let and const.
  • Hoisting is primarily about Declarations: While some may say "variables are hoisted", it's more precise to state that variable declarations are hoisted. The initialization still happens where it originally was.

Best Practices

To avoid potential hoisting-related issues, I strongly advocate:

  • Declaration variables at the top of their scope: This enhances code readability and maintainability.
  • Preferring let and const over var: These block-scoped variables prevent the ambiguity of var's behavior.
Last Update: 15:43 - 18 April 2024

On this page