Skip to content

Edvins Antonovs

Hoisting in JavaScript

In JavaScript, hoisting is a term used to describe the behavior of variable declarations. In JavaScript, when you declare a variable, it is automatically assigned to the top of the current scope. This is called hoisting.

For example, consider the following code:

1console.log(x); // undefined
2var 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); // undefined
3x = 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 5 to 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 defined
2let 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.

© 2024 by Edvins Antonovs. All rights reserved.