Understanding Hoisting: A Crucial Concept in JavaScript

devlawrence

Amrasakpare Lawrence

Posted on April 21, 2023

Understanding Hoisting: A Crucial Concept in JavaScript

Hoisting is a common concept in JavaScript that programmers use frequently in their projects, But many of us don’t know what it is or how it works. In this article, we’ll explore the basics of hoisting and how it works so that you can gain a better understanding of this important concept.

What is Hoisting ?

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their scope by the JavaScript engine. This means that you can use a variable or function before it has been declared in your code, and JavaScript will still understand what you mean.

So basically, you can say that Hoisting is like a teacher who collects all the homework before class starts and then hands it out to everyone when class begins. In JavaScript, all variable declarations are collected before the code runs and then assigned values when the code runs. This means that you can use a variable before it has been declared. However, only the declaration is hoisted, not the initialization. For example, if you declare a variable and then initialize it later, the value of the variable will be undefined until it is initialized.

💡 Hoisting simply takes some of the code you write and move them to the top of the JavaScript file automatically for you.

I know it’s kind of difficult to wrap your head around at first. So let’s break it down further with some examples.

Hoisting can be broken down into two category which are;

  • Variable Hoisting
  • Function Hoisting

Variable Hoisting

Variables are hoisted to the top of their scope.


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

As you can see from the code above, the variable x is declared after it is used in the console.log statement. However, because of hoisting, the declaration of x using the var keyword is moved to the top of the scope like this 👇🏽

var x = undefined;
Enter fullscreen mode Exit fullscreen mode

which means that the value of x is undefined at the time of the console.log statement.

Hope it makes sense now ?

However, when we use the let or const keywords, the output on the console will be different because let or const are never hoisted at all.

Let’s see an example 👇🏽

console.log(x);
const x = 10;
Enter fullscreen mode Exit fullscreen mode

Here is the output 👇🏽

Error Message

So since we are in a modern world (es6 /es7 ) 😅, I would advice you to stop using the var keyword as much as possible and start using other keywords such as const or let.

Function Hoisting

Similarly, function declarations are also hoisted to the top of their scope. But unlike variable hoisting, function hoisting allows us to call a function before it is defined. For example 👇🏽

greeting(); // Output: "Hello, world!"

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

From the code above, the function greeting is called before it is declared. However, because of hoisting, the function declaration is moved to the top of the scope, which means that the function can be called anywhere in the code.

It's important to note that only the declarations of variables and functions are hoisted, not their assignments or initializations. Therefore, it's still good practice to declare variables and functions at the beginning of their respective scopes to avoid any confusion or unintended consequences. Here is an example of what I’m trying to say 👇🏽


//varible declaration
const x = 10;
console.log(x);

//function declaration
function greeting(){
    console.log("Hello, world")
}

greeting()

Enter fullscreen mode Exit fullscreen mode

If you also noticed earlier, I said “function declarations are hoisted”. So I’m guessing your next question should be what about “function expressions”?

Well, before we talk about that I would want you to think about the question and try to provide an answer to it with the knowledge you have so far.

If you can’t even think of an answer because you don’t know what “function expression” is. Here is a basic explanation 👇🏽

A function expression is a way to define a function as a value within an expression. It is different from a function declaration, which defines a named function as a standalone statement (like the example we just did).

I’m pretty sure you now have an answer to the question. But if you still don’t have an answer that’s also fine because we are learning together.

The answer to the question is that function expression are not hoisted because as we just learned earlier on, variable assignments aren't hoisted.

So, when we try to call the variable that a function expression is assigned to, we will get a TypeError or ReferenceError, depending on the variable's scope:

Let’s see an example of such instance 👇🏽

add(2, 3)

let add = function(a, b) {
  return console.log(a + b);
};

//output:
//Uncaught ReferenceError: Cannot access 'add' before initialization
Enter fullscreen mode Exit fullscreen mode

From the example above, we created a variable add using the let keyword with a function expression assigned to it. So when we trying calling that function, we are going to get that commented error you are seeing because the function is inside a function expression and not a declaration itself.

Whew!!. That was a lot to take in 😅.

Summary

Here are some important things I want you to put in mind if you want to understand hoisting much faster.

  • Hoisting simply takes some of the code you write and move them to the top of the JavaScript file automatically for you.
  • Because of the confusion that var hoisting can create, you should to use let or const more often.
  • Function declaration are hoisted and Function expression are not hoisted.
  • To avoid confusion and bugs in your code, it's best practice to declare your variables and functions at the top of their respective scopes .

Conclusion

That’s all guys, thanks for taking your time to read this article. It really took me some time to understand how hoisting works so just take all the time you need to understand it. Till next time 😀

💖 💪 🙅 🚩
devlawrence
Amrasakpare Lawrence

Posted on April 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related