Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a purpose to hoisting variables?

I've been learning a lot of Javascript lately and I've been trying to understand the value (if there is any) of hoisting variables.

I understand (now) that JS is a two pass system, it compiles and then executes. Also, I understand that the var keyword 'exists' in the lexical scope it was declared, hence why it's 'undefined' if it's called before it's assigned a value by the engine.

The question is, why does that even matter? What use is there to hoisting variables that you can't do without hoisting? I feel like it just creates less-readable code with no gain ...

is there an example(s) of where hoisting variables is useful?

like image 988
kevin Avatar asked Feb 03 '23 21:02

kevin


1 Answers

"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);
        };
    }
};
like image 112
Bergi Avatar answered Feb 06 '23 09:02

Bergi