javascriptecmascript-6hoisting

Is there any benefit from hoisting?


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.


Solution

  • 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.