Javascript – hoisting

Recently I had to refactor a very large react class component into a function component, the overall goal was to keep the business logic the same, but add thourough typing so the risk of regressions from a much larger refactor later would be lower.

I ran into a problem with this, it seemed at first that I would be unable to avoid doing a refactor of business logic because, after converting class methods into anonymous functions in my new function component, I was now getting warnings about many functions being used before they were declared. This was frustrating, as fixing this with code changes – creating more abstraction etc, would result in changes to the business logic, and therefore add more risk of regression, so I instead decided that it might be more pragmatic to temporarily make use of hoisting. If you are not aware of what hoisting is you can read more here.

Below is an example that shows it in action.

The console output here would be:

I don’t recommend getting into the habit of declaring functions after they are used, regardless of hoisting, but this was just an example of when hoisting was a pragmatic temporary solution, so be aware of it!