EDDYMENS

Published 5 months ago

What Is Hoisting?

Hoisting is a term you might hear when learning JavaScript. It is a concept that can seem confusing at first, but it’s quite simple once you understand it.

In JavaScript, hoisting means that you can use functions and variables before you declare them. This happens because JavaScript moves these declarations to the top of the code during the JIT compilation [β†’] phase. However, only the declarations are moved, not the actual assignments or initializations.

Example

Let’s look at an example with a variable:

01: console.log(name); // Output: undefined 02: var name = 'John';

In the above code, you might expect an error because name is logged before it is declared. But instead, it prints undefined. This happens because JavaScript hoists the variable declaration to the top. So the code is interpreted like this:

01: var name; 02: console.log(name); // Output: undefined 03: name = 'John';

Now let’s see an example with a function:

01: greet(); // Output: Hello! 02: 03: function greet() { 04: console.log('Hello!'); 05: }

Here, the function greet is called before it is declared, but it still works. This is because the function declaration is hoisted to the top.

However, be careful with variables declared using let or const. These are not hoisted in the same way. If you try to use them before they are declared, you will get an error:

01: console.log(age); // ReferenceError: Cannot access 'age' before initialization 02: let age = 30;

Conclusion

In summary, hoisting allows you to use functions and variables before they appear in the code. Understanding hoisting can help you write cleaner and more predictable JavaScript code. Just remember that var is hoisted, but let and const are not in the same way. Functions are also hoisted, which allows you to call them before their declaration.

Here is another article you might like 😊 What Is A Benchmark In Programming?