Is there a purpose to hoisting variables?

Solution 1:

"Hoisting" is necessary for mutually recursive functions (and everything else that uses variable references in a circular manner):

function even(n) { return n == 0 || !odd(n-1); }
function odd(n) { return !even(n-1); }

Without "hoisting", the odd function would not be in scope for the even function. Languages that don't support it require forward declarations instead, which don't fit into JavaScripts language design.

Situations that require them might arise more often that you'd think:

const a = {
    start(button) {
        …
        button.onclick = e => {
            …
            b.start(button);
        };
    }
};
const b = {
    start(button) {
        …
        button.onclick = e => {
            …
            a.start(button);
        };
    }
};

Solution 2:

Not really. The only thing I can think of where it would be helpful is if you are writing code in a hurry and you happen to declare it later on. So it doesn't really matter, it's a weird addition to JS that a lot of people don't really even know about because utilizing it feels backwards and inefficient.

Solution 3:

There is no such thing as hoisting. Hoisting is merely a side effect of the compile phase that occurs and the fact that Javascript is lexically scoped. When the compiler comes to the compile phase it puts all variable and function declarations in memory as it figures out the lexical scopes that exists in the program. But there is no hoisting function or keyword or module. In fact it wasn't even reference in the Ecmascript spec before the es2015 release.

At the end of the day, hoisting is one of those million dollar words we all use, often because its easier to use rather than explain and discuss the compilation process that javascript goes through.

My suggestion would be to either read through the Ecmascript specs, work through a javascript engine source like v8, or read up on Kyle Simpson's work. He wrote a great series called You Don't Know JS.

Hope this helps!

Hoisting is a term you will not find used in any normative specification prose prior to ECMAScript® 2015 Language Specification. Hoisting was thought up as a general way of thinking about how execution contexts (specifically the creation and execution phases) work in JavaScript. However, the concept can be a little confusing at first. Conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. <- From the Mozilla docs

https://developer.mozilla.org/en-US/docs/Glossary/Hoisting