What is the Difference Between Hoisting and Closures in javascript?

Zia Ur RehmanZia Ur Rehman
4 min read

Understanding the Difference Between Hoisting and Closure in JavaScript

JavaScript is a dynamic and powerful language, and when you start learning it, you’ll encounter a couple of tricky concepts: hoisting and closures. Both are fundamental but can be confusing at first. In this article, we'll explain these concepts in simple, easy-to-understand terms, using real-life examples to make things clearer.


What is Hoisting?

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase, before the code has actually been executed.

Real-time Example of Hoisting:

Imagine you’re at a meeting, and before the meeting starts, the agenda and the people assigned to each task are announced. Even though the meeting hasn’t officially begun, everyone already knows what they will do. Similarly, hoisting is like the JavaScript engine "preparing" your variables and functions before it starts running your code.

Let’s look at an example:

console.log('Hoisting');
console.log(x); // undefined due to hoisting
var x = 5;

In the above code, you might expect myVar to be logged as 10, but it logs as undefined. This is because the declaration (var myVar) is hoisted to the top of the code, but the assignment (myVar = 10) stays where it is. So, at the time console.log(myVar) is called, the variable myVar exists, but it hasn't been assigned a value yet.

How hoisting works:

//example 1
var myVar = 10; // Regular declaration and assignment
console.log(myVar); // Logs: 10
// Functions are also hoisted completely, meaning they can be used before being declared.
//example 2
myFunc();
function myFunc() { console.log('Hello'); }m

l

However, in the case of functions, the function declaration itself is hoisted entirely, which means you can call the function before its actual definition in the code.

//heres the example of hoisting with functions
example
myFunc(); 
function myFunc() {
  console.log("Hello, World!");
}

What is Closure?

A closure in JavaScript is a function that "remembers" its lexical scope (the environment in which it was created) even after that scope has finished executing.

In simpler terms, closures allow a function to continue accessing variables from its outer function, even after the outer function has returned.

Real-time Example of Closure:

Imagine you have a kitchen (the outer function), and within that kitchen, you have an oven (the inner function). Even after the kitchen is closed, the oven can still "remember" the ingredients that were placed inside it. In a similar way, closures "remember" the variables from their outer function even after the outer function has finished.

Let’s see a closure in action:

//closure
function outer() {
    let count = 0;
    return function inner() { // the function which is remembring the variable of its outer scope
      count++;
      console.log('Closure');
      console.log(count);
    };
  }
  const counter = outer(); //here outer function is executed and inner function returned and stored in
//counter variable
  counter(); // 1
  counter(); // 2

In the example above, inner function can access outer variable which is counter, even though outer function has already finished executing. This is the essence of a closure — the inner function remembers the variables from the outer function.


Key Differences Between Hoisting and Closure

  1. What They Do:

    • Hoisting: Moves variable and function declarations to the top of their scope during the compilation phase.

    • Closure: Refers to a function that has access to variables from its outer function, even after the outer function has executed.

  2. When They Happen:

    • Hoisting: Happens before the code execution begins, during the compilation phase.

    • Closure: Occurs during runtime when the inner function is called and continues to have access to the outer function’s variables.

  3. Use Cases:

    • Hoisting: Helps in organizing your code, so you can refer to variables and functions before they are declared in your code.

    • Closure: Useful when you need to keep track of data across different function calls (e.g., private variables, callbacks, event handlers).


Summary

Both hoisting and closures are essential parts of JavaScript, but they serve different purposes. Hoisting allows us to access variables and functions before their declaration, while closures allow functions to "remember" variables from their surrounding environment, which is incredibly useful when dealing with things like private variables, callbacks, and asynchronous code.

Understanding these concepts and how they work will make you a much better JavaScript developer. Just remember:

  • Hoisting is like pre-loading your variables and functions at the start.

  • Closures are like giving your functions a "memory" of their environment, allowing them to access variables from an outer function long after that outer function has finished executing.

Thanks and Happy Coding.

0
Subscribe to my newsletter

Read articles from Zia Ur Rehman directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Zia Ur Rehman
Zia Ur Rehman

🧐 Are you facing challenges like slow website performance, poor user experience, cross-browser issues, and difficulty integrating with back-end systems, all while trying to manage business growth without a streamlined digital solution? 🤔 Are you struggling to reach a wider audience, improve customer engagement, and stay competitive without a web app, while dealing with inefficient operations, limited scalability, and missed revenue opportunities? 🚀 Build a web app to expand reach, improve engagement, and streamline operations for growth. ⚙️ Optimize performance, enhance user experience, and integrate systems with a smooth, scalable solution. 👨‍💻 I am Zia-Ur-Rehman a MERN Developer with experience in building scalable and high-performing web applications that solve buisness Problems. I worked with the startup to Help their clients by developing highly scalable webApps to make their global buisness mangable with one click across globe. ✅ Frontend Development to create responsive, user-friendly interfaces that solve the problems of your audience. ✅ Figma to Next.js Functional App transforming your designs into interactive, high-performance Web apps. ✅ Web App Development to expand your reach and improve customer engagement.✅ Performance Optimization for faster load times and seamless user experience.✅ Cross-Browser Compatibility ensuring your app works perfectly everywhere.✅ Backend Integration to streamline operations and boost business efficiency. If you have an idea that will capture market share, why are you waiting? 🚀 DM me today or email me (emailtozia0@gmail.com) and get started!