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?
"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);
};
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With