Hoisting variables and function declarations in Javascript happens when the variable object is created for an execution context. See my last article to read about execution contexts. Before running any code your browsers javascript engine scans the current execution context for variable and function declarations. In plain terms, functions and variables are found before code is executed so javascript knows how to compute once it encounters them in execution mode. This process is known as hoisting by the javascript community.
Function declaration hoisting
For each function declaration (function myFunc()
) encountered, a property is created in the variable object that acts as a pointer to that function. This pointer allows you to call a function in your code before it has been declared. Try the code below in your console.
myFunc(10);
function myFunc(num) {
console.log(`Your number is ` + num)
};
It's worth mentioning that function expressions are treated as variables. Calling a function expression before the declaration will not run the function.
runCode();
var runCode = () => {
console.log("I'm a variable, that points to a function. I don't get defined until execution.")
}
Variable declaration hoisting
Your browsers engine also looks for variable declarations. For each variable declaration, a property is created in the variable object and (depending on the keyword used) set to undefined.
var
Declaring a variable using var
will set that variable to undefined
when hoisting. This allows you to call your variable before declaring. Of course, the value will be undefined
. Try the code below in your console.
console.log(age);
var age = 23;
console.log(age);
const && let
Using const
or let
to declare your variable will create the pointer like normal, but the variable will not be initialized (aka set to undefined
). If you call your variable you'll get an Uncaught ReferenceError
.
console.log( cat, dog );
const cat = "Ozma";
let dog = "Pippin";
What hoisting does not do.
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 MDN
Top comments (0)