I'm trying to wrap my head around a few things when it comes to hoisting and variable mutation.
Function declarations are hoisted over variable declarations but not over variable assignments according to https://scotch.io/tutorials/understanding-hoisting-in-javascript. This is extremely confusing because I thought only variable declarations and function declarations get hoisted.
var double = 22;
function double(num) {
return (num*2);
}
console.log(typeof double); // Output: number
so with hoisting it should look like
function double(num) {
return (num*2);
}
var double;
double = 22;
console.log(typeof double); // Output: number
If variable assignment takes precedence over function declaration why isn't double = 22 above the function declaration? Another example
var double;
function double(num) {
return (num*2);
}
console.log(typeof double); // Output: function
With hoisting pulling the function above the variable declaration the console should log undefined shouldn't it? With variable mutation the last assignment is what the program should execute.
(From the comments)
If variable assignment takes precedence over function declaration why isn't
double = 22above the function declaration?
Variable name declarations are hoisted, but assignments (=) are never hoisted.
Then what does "Variable assignment takes precedence over function declaration" mean?
It makes no sense at all, really. An assignment and a declaration are two totally unrelated things, they don't "take precedence" over each other. I guess it's supposed to mean just that you can always assign a mutable variable, and it will hold the assigned value afterwards, regardless of where/how the variable was declared (with var or function).
How in my last example even though function is hoisted above the variable declaration the output is still function instead of undefined?
Because "takes precedence" doesn't refer to order, as in "is hoisted above the other". Declarations don't really have any order for our purposes, all variables are created at once (that's what "hoisting" actually means).
The precedence refers to the value that the variable is initialised with, undefined for vars and function objects for functions. The rule means that when there is a function declaration with the same name as a var declaration, then the variable is initialised with the function.
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