Closures: Part II | Diving Deeper

Closures: Part II | Diving Deeper

Check out Part-I for a brief overview on Closures in Javascript.

?? Now, let's dive deeper into Closures.

?? As promised earlier, I am keeping it simple and fun! So, that even your pet parrot can understand! ??

Let's remember the why?

? In the previous article, I mentioned that Closures are used everywhere in JavaScript; right from the callbacks and event handlers to modules and function factories. Let's dive deeper into these applications! ??


?? Encapsulation

Imagine you have a secret recipe you don’t want to share with everyone. Closures help you keep those secrets safe!

function secretRecipe() {
  let ingredient = 'love';  // The Secret is safe here :)

  return function() {
    console.log(`The secret ingredient is ${ingredient}`);
  }
}

const revealSecret = secretRecipe();
revealSecret(); 
// Displays :The secret ingredient is love        


?? Maintaining State

Think of it as having a personal assistant who always remembers your schedule. You don’t have to remind them every day!

function schedule() {
  let task = 'Meeting at 10 AM';  // Somehow it's always at 10AM ;)

  return function() {
    console.log(`Today’s task: ${task}`);
  }
}

const mySchedule = schedule();
mySchedule(); 
// Displays : Today’s task: Meeting at 10 AM
        


?? Function Factories

Need customized greetings? Closures can help you create functions on the fly, just like having a customizable greeting card service!

function createGreeting(greeting) {
  return function(name) {
    console.log(`${greeting}, ${name}!`);   // Choose your greetings wisely -_-
  }
}

const sayHello = createGreeting('Hello');
sayHello('Alice'); 
// Displays : Hello, Alice!

const sayHola = createGreeting('Hola');
sayHola('Isabella')
// Displays : Hola, Isabella!
        


?? Callbacks and Event Handlers

Imagine you’re at your pizza trying out phase ??, and you want to remember which pizzas you ordered from which restaurant. Closures help you keep track of that information!

function orderMyPizza(url) {

  fetch(url).then(

    function(response) {

        console.log(`This pizza was ordered from ${url}`);

  });

}

orderMyPizza('https://parrotpizzas.com/order/vg'); 
// Displays : Pizza ordered from https://parrotpizzas.com/order/vg

orderMyPizza('https://petspizzeriass.com/order/nvg'); 
// Displays : Pizza ordered from https://petspizzeriass.com/order/nvg        

In this scenario, the orderMyPizza function is like your magical pizza tracker, always remembering where each delicious slice came from. ??

Here, we're simply logging the URL, however, you can do so much more! Like Send a message to inform your homies ??????, track the spots you've tried out so far in a report and so much more!


?? Module Pattern

Need to keep some things private in your code? Think of closures like having a secret stash of cookies ?? hidden away in a locked drawer that only you can open! ????

The Module Pattern uses closures to create private and public parts within your code, ensuring that only certain functions can access the hidden data.

 const cookieJar = (function() {

  let secretCookie = 'Chocolate Chip';

  function eatCookie() {

    console.log(`Yum! Enjoying a ${secretCookie} cookie!`);

  }

  return {

    revealCookie: function() {

      eatCookie();

    }

  }

})();

cookieJar.revealCookie(); 
// Displays : Yum! Enjoying a Chocolate Chip cookie!        

In this tasty ?? example, cookieJar is like your secret cookie stash. The secretCookie is safely hidden away, and only you have the key to enjoy it. ????


Wrapping Up:

Closures are a fundamental feature in JavaScript. Understanding closures unlocks a deeper mastery of JavaScript ?????? and enhances your ability to solve complex programming problems. ??

So, next time you’re coding in JavaScript, give a nod ???? to closures. They’re the unsung heroes making your code awesome! ??

Happy coding! ????

#JavaScript

#Closures

#Coding

#WebDevelopment

#LearnToCode

#TechFun


?? Note: AI assistance was incorporated to create this post! ??

Rohit Guru

NIT Bhopal | Full Stack Developer | React.js | JavaScript | Node.js | Express.js | HTML | CSS || Data Science

10 个月

Very helpful!

要查看或添加评论,请登录

Bikash Bhagat的更多文章

  • Is SEO Better in NextJS When Compared to React?

    Is SEO Better in NextJS When Compared to React?

    Welcome to the Battle! ?? In one corner, we have React ??, the fan-favorite JavaScript library. In the other, we have…

    2 条评论
  • HOC : Higher Order Components | A Brief Overview

    HOC : Higher Order Components | A Brief Overview

    ?? Let's dive into a super cool and powerful concept in React: Higher-Order Components (HOCs). I promise to keep it fun…

    2 条评论
  • Closures: Part I | A Brief Overview

    Closures: Part I | A Brief Overview

    ?? Let's understand one of the coolest yet confusing concepts in JavaScript: Closures. Don't worry, I promise to keep…

  • Curry In My Code! ??

    Curry In My Code! ??

    ?? Ever heard of currying? Nope, it’s not the spicy dish you’re thinking of ??, but it might just spice up your…

    5 条评论

社区洞察

其他会员也浏览了