Hoisting in JavaScript Explained
Michael Mitrakos
5 min read
Having worked across sites raking in over 50 billion website visits annually with Higglo Digital I write about tech topics and teach engineers to have solid foundations that will help them get ahead in their career. I also build awesome products for digital nomads — check it out!
JavaScript eBook
I’ve written an eBook on JavaScript that will take you from beginner to professional. Having been in your shoes moving to making over $200,000 per year in just a few years as a software engineer, I know exactly what it takes to get there. Check out the ebook now!
Hoisting is a concept in JavaScript that refers to the behavior of variable declarations and function declarations being moved to the top of their respective scope during the compilation phase. This can lead to some unexpected behaviors and it is important for developers to understand how hoisting works in order to write correct and predictable code.
In JavaScript, variables can be declared using the var keyword, as well as the more recent let and const keywords introduced in ECMAScript 2015. Function declarations can also be made using the function keyword.
When a JavaScript program is compiled, declarations using these keywords are automatically moved to the top of their respective scope. This means that, regardless of where a variable or function is declared within the code, it will be treated as if it were declared at the top of its scope.
For example, consider the following code:
console.log(num); // Output: undefined
var num = 5;At first glance, it may seem like this code should throw a reference error, as num is being accessed before it is declared. However, due to hoisting, the declaration of num is actually treated as if it were written at the top of the code, like this:
var num;
console.log(num); // Output: undefined
num = 5;As a result, the code will not throw an error and will instead output undefined.
It’s important to note that hoisting only affects declarations, not assignments. In the example above, the assignment of 5 to num is not hoisted and is executed in the original location within the code. This means that the value of num will not be defined until the assignment is executed.
Hoisting also affects function declarations in a similar way. Consider the following code:
foo(); // Output: "foo"
function foo() {
console.log("foo");
}Again, it may seem like this code should throw an error, as the function foo is being called before it is declared. However, due to hoisting, the declaration of foo is treated as if it were written at the top of the code, like this:
function foo() {
console.log("foo");
}
foo(); // Output: "foo"As a result, the code will not throw an error and will correctly output "foo".
It’s important to keep in mind that hoisting can lead to some unexpected behaviors if not understood properly. For example, consider the following code:
console.log(num); // Output: undefined
var num = 5;
console.log(foo); // Output: "foo"
var foo = function() {
console.log("foo");
};In this code, the first console.log statement will output undefined as expected, due to hoisting of the num declaration. However, the second console.log statement may produce an unexpected result, as it is accessing a function expression assigned to a variable.
Because function expressions are not hoisted, the second console.log statement is actually accessing the value of the foo variable before it has been assigned a function. As a result, the output will be "foo", the default value for a function in JavaScript.
To avoid these types of issues, it is generally a good practice to declare all variables and functions at the top of their respective scope. This ensures that there is no confusion about the value of a variable or the existence of a function, and can help prevent unexpected behaviors caused by hoisting.
It’s also important to keep in mind that the let and const keywords, introduced in ECMAScript 2015, do not behave the same way as the var keyword when it comes to hoisting. Declarations made using let and const are not hoisted to the top of their scope in the same way as var declarations.
Instead, declarations made using let and const are hoisted to the top of their scope, but their assignment is not. This means that, unlike var, attempting to access a let or const variable before it has been declared will result in a reference error.
For example, consider the following code:
console.log(num); // Throws a reference error
let num = 5;Unlike the var example, this code will throw a reference error, as the let declaration of num is not hoisted in the same way as a var declaration.
In summary, hoisting is a fundamental concept in JavaScript that refers to the behavior of declarations being moved to the top of their respective scope during the compilation phase. Understanding hoisting can help developers write correct and predictable code, and avoid unexpected behaviors caused by declarations being accessed before they are defined.
JavaScript eBook
I’ve written an eBook on JavaScript that will take you from beginner to professional. Having been in your shoes moving to making over $200,000 per year in just a few years as a software engineer, I know exactly what it takes to get there. Check out the ebook now!
I founded Higglo Digital and we can help your business crush the web game with an award-winning website and cutting-edge digital strategy. If you want to see a beautifully designed website, check us out.
I also created Wanderlust Extension to discover the most beautiful places across the world with highly curated content. Check it out!
Related reading
Master Recursion in JavaScript: Tips, Tricks, and Examples
Diving into the world of JavaScript, we often encounter concepts that seem daunting at first glance. Recursion is one such concept, a powerful tool that, when…
JavaScript Promises Explained for Beginners: Master Async Code
If you’ve ever found yourself scratching your head over asynchronous operations in JavaScript, you’re not alone. It’s a common hurdle for beginners, but that’s…
Beginner’s Guide to JavaScript Cross-Browser Compatibility
Ever found yourself scratching your head wondering why your JavaScript code works like a charm in Chrome but throws a tantrum in Internet Explorer? Welcome to…