DEV Community

Yuta Kusuno
Yuta Kusuno

Posted on • Updated on

[JS] Look back on Hoisting

In JavaScript, understanding hoisting is crucial for any developer. Hoisting can be a tricky concept at first, but once you grasp it, you will have a solid foundation for writing efficient and error-free code. I will explore how it works, and provide examples to help you master this essential JavaScript concept.

What is Hoisting?

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase. This allows you to use variables and functions before they are declared in your code.

Variables Hoisting

Let us see an example:

console.log(a); // Output: undefined
var a = 5;
console.log(a); // Output: 5
Enter fullscreen mode Exit fullscreen mode

In this example, the variable a is hoisted to the top of the scope during the compilation phase, resulting in the first console.log(a) printing undefined. However, the second console.log(a) prints 5 because the variable has been assigned the value by that point in the code.

Function Hoisting

Function declarations are also hoisted. Consider the following example:

sayHello(); // Output: Hello!

function sayHello() {
  console.log("Hello!");
}
Enter fullscreen mode Exit fullscreen mode

In this case, the sayHello function is hoisted to the top of the scope, allowing us to call it before its actual declaration.

Variable Hoisting vs. Function Hoisting

It is important to note that while both variable and function declarations are hoisted, there are differences in how they are handled during hoisting. Function declarations are completely hoisted, including both the function name and its implementation. On the other hand, variable declarations are hoisted, but only the variable name is moved to the top, not the assignment.

console.log(myVariable); // Output: undefined
var myVariable = "I am hoisted!";

hoistedFunction(); // Output: "I am hoisted!"
function hoistedFunction() {
  console.log("I am hoisted!");
}
Enter fullscreen mode Exit fullscreen mode

Good ideas

To avoid confusion and potential bugs related to hoisting, it is a good practice to declare variables at the top of their scope and define functions before using them.

That is about it. Happy coding!

Top comments (0)