What is variable hoisting in Javascript

By FoxLearn 12/18/2024 7:25:42 AM   18
Variable hoisting refers to how JavaScript automatically moves the declarations of variables to the top of their containing scope during the execution phase, while the initialization remains in its original position.

In JavaScript, when you declare a variable using the var keyword, the declaration is hoisted to the top of its scope. This means you can use the variable before it's declared, but its value will be undefined until it is assigned.

For example:

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

In the example above, the variable x is hoisted to the top, so it can be used before being declared without throwing an error. However, its value is undefined until it is assigned the value 5.

It’s important to note that only the declaration is hoisted, not the initialization. So, while the variable is hoisted, the actual assignment of a value is not affected by hoisting.

The let and const keywords, introduced in ECMAScript 6 (ES6), do not hoist variable declarations to the top of their scope like var. They have block-level scope, meaning they are only accessible within the block they are defined in.

console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;
console.log(x); // 5

In this example, using let instead of var results in a ReferenceError because the variable x is not hoisted. It is only accessible after the declaration statement. This behavior helps prevent potential bugs and makes the code easier to understand when using block-scoped variables.

Similarly, const variables do not hoist and have block-level scope. The key difference is that const variables cannot be reassigned once they are initialized.

console.log(x); // ReferenceError: Cannot access 'x' before initialization
const x = 5;
console.log(x); // 5

x = 15; // TypeError: Assignment to constant variable

In this case, the const variable x cannot be reassigned a new value after it is declared and initialized, making const useful for variables that should not change.

To summarize:

  • var hoists the variable declaration to the top.
  • let and const do not hoist and have block-level scope.