So I thought I understood hoisting in JavaScript until I saw something like this:
function hoist(a) {
console.log(a);
var a = 10;
}
hoist(5);
The code above outputs 5
, not undefined
!
As per my understanding, the function looks like this to the interpreter:
function hoist(a) {
var a; // This should overshadow the parameter 'a' and 'undefined' should be assigned to it
console.log(a); // so this should print undefined
a = 10; // now a is assigned 10
}
So what's happening here?
Yes you can, as long as you don't forget the var keyword : the scope of a variable is either the function in which it is declared or the global scope.
Some ways to avoid hoisting are: Use let or const — As explained above, using let or const instead of var would throw an exception and not let the program run, hence helping catch the issue earlier. Use function expressions instead of function declarations.
let and const hoistingVariables declared with let and const are also hoisted but, unlike var , are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.
Therefore, in your case, the variables will be passed from the main driver to the individual functions by reference. So, yes, you can have variables of the same name in different scopes.
You would be right if the var was called b
, but the var a
already exists. redeclaring a javascript variable that already exists doesn't do anything. It will not change the value to undefined. Try it.
function hoist(a) {
var a; // no op, does not change a to undefined.
console.log(a);
a = 10;
}
hoist(18);
This falls back in the section Only declarations are hoisted in the MDN (to link some documentation, at least).
The second example given there is the exact one you're looking for:
num = 6;
console.log(num); // returns 6
var num; // or, really, var num = whatever.
To just recall what is said:
If you declare the variable after it is used, but initialize it beforehand, it will return the value.
Hoisting a variable means that the variable name is known to the compiler from the beginning of the block. It does not re-introduce, overwrite, clear or reset the variable if it already exists.
Until something is assigned, the value of that variable is undefined
, but hoisting itself does nothing to the value of the variable.
It so happens that a function parameter is also a way of declaring a variable, like an invisible var
statement, followed by an assignment that happens as the function gets called, before any of the actual function body executes.
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