top of page
Logo der Online Agentur mdwp

Hoisting

Hoisting isn't a term exclusive to React JS but it's a general JavaScript behavior. Hoisting in JavaScript is a mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase, before the code has been executed.

What does it mean to be moved to the top? It means that you can use a function or a variable before it has been declared. Fundamentally, this is what hoisting does.

Here is a simple example:

```javascript
console.log(myVar); // Returns 'undefined', but code still runs because myVar was hoisted to the top of the scope and declared. It isn't initialized until later.
var myVar = 5;
console.log(myVar); // Returns '5'
```

Note that only declarations are hoisted, initializations are not. If you try to use a variable before you initialize it, it will result in the output "undefined", because hoisting only moves the declarations.

Also, JavaScript only hoists declarations, not initializations. If a variable is declared and initialized after using it, that variable will be undefined. Here is an associated example:

```javascript
num = 6; // Assign 6 to num
console.log(num); // Displays 6
var num; // Declaration is hoisted to the top
```
In this case, the output is 6 as well because num was defined before the console.log() command.

bottom of page