DEV Community

Cover image for Hoisting
Joe Avila
Joe Avila

Posted on • Updated on

Hoisting

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)
};
Enter fullscreen mode Exit fullscreen mode

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.")
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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
Cover image: just a cool photo found while searching hoisting on creative commons
"Great hoists, Hulett and Brown electric at work" by Boston Public Library is licensed under CC BY 2.0

Top comments (0)