For example, consider the following code:
1console.log(x); // undefined2var x = 5;
At first glance, it might seem that this code would throw a reference error, since
x is not defined before it is used. However, because of hoisting, the declaration of
x is actually treated as if it appears at the top of the code, like this:
1var x;2console.log(x); // undefined3x = 5;
This means that the value of
x is undefined when it is logged to the console, but it is defined later in the code.
Hoisting only affects the declaration of variables, not the assignment of values to them. In the example above, the assignment of the value
x is not hoisted and still occurs at the point in the code where it is written.
It's important to note that hoisting only applies to declarations, not initializations. For example, the following code will still throw a reference error, because the initialization of
y is not hoisted:
1console.log(y); // ReferenceError: y is not defined2let y = 5;
In general, it's a good practice to always declare your variables at the top of the scope to avoid any confusion or unexpected behavior due to hoisting.
Sign up to get updates when I write something new. No spam ever.Subscribe to my Newsletter