educative.io

Variable hoisting

In this lesson, it says “Variables are added to the corresponding context’s variable object only when they are declared”. However, I thought that because of hoisting, JavaScript will move all variable declarations to the top of the current scope. So you can do something like this:
var x; // Declare x
x = 5; // Assign 5 to x

Could you clarify? It would be helpful for the lesson to cover “let” for variable declarations too and describe the difference between “var” and “let”?


Course: Web Development: Unraveling HTML, CSS, and JavaScript - Learn Interactively
Lesson: https://www.educative.io/courses/web-development-unraveling-html-css-js/qZpBPDrVwn0

Hi @Yunfei_Xie !!
JavaScript hoists variable declarations to the top of their scope during the compilation phase. This means that we can use a variable before it’s explicitly declared in the code. However, there is a difference between the behavior of var and let when it comes to hoisting.

For variables declared with var, the declaration is hoisted to the top of the current scope, but the initialization (assignment) remains in place. This means that the variable is hoisted with an initial value of undefined until the assignment is encountered in the code.

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

In the above example, the variable x is hoisted to the top, but its value is undefined at that point. The assignment x = 5 happens later in the code.

On the other hand, variables declared with let and const are also hoisted to the top of the current scope, but they are not initialized (unlike var). This is called the “temporal dead zone” (TDZ). If we try to access a let or const variable before its declaration, we’ll encounter a ReferenceError.

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

In the example above, trying to access the variable y before its declaration results in a ReferenceError because the TDZ prevents accessing the variable until it’s fully declared.

In summary, both var and let declarations are hoisted to the top of their scope, but var variables are initialized with undefined while let variables (and const variables) are not initialized until their declaration is reached. The TDZ for let and const variables provides a more strict behavior, avoiding accidental use before the declaration and promoting better code practices.
I hope it helps. Happy Learning :blush:

2 Likes