Is there any benefit from hoisting?

Viewed 558

I would like to see which are the benefits of hoisting, if there's some... I looked for an answer but they only explain what is it, I would like to know is there's an actual benefit that I can use to write better code.

It seems that with the use of const and let, javascript is actually enforcing to avoid hoisting, not to mention that some linters actually enforce to declare functions and variables at the top from where they're called.

2 Answers

The main benefit of hoisting is that functions don't have to be declared in a specific order in order to work properly. The interpreter makes a pass over a function of code and finds all the function declarations within that function and makes them available to code anywhere in the scope (hoisting them) whether the code referring to the functions is before or after where the function declarations are located. It also allows A to call B and B to call A without running into declaration ordering issues.

Variable hoisting is rarely used anymore now that we have const and let which are block scoped and cannot be used before declaration. So hoisting is mainly useful for function declarations now.

In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. It allows us to call functions before even writing them in our code.

Note: JavaScript only hoists declarations, not the initializations.

Related