How to explain JavaScript Closure to a 5 years old kid
Paper Coding

Paper Coding @papercoding22

About: Coding on the paper first

Location:
Ho Chi Minh city, Viet Nam
Joined:
Jan 21, 2021

How to explain JavaScript Closure to a 5 years old kid

Publish Date: Feb 4 '21
201 16

Lazy to read. Show me the code.

// 👶 How to explain closure to a 5 years old kid

/** 
* Closure is like a candy factory
* You send the factory an order to make candies for you with your favorite flavor.
* The factory will pick the right expert for you,
* And it send back to you an expert's contact.
* Now whenever you need, you just call and submit the quantity.
* That expert will take care all the rest for you.
*/
const candyFactory = (flavor) => {
  const experts = {
    Chocolate: {
        name: 'Tim',
        secretRecipe: '🍫',
    },
    Strawberry: {
        name: 'Alex',
        secretRecipe: '🍓',       
    }
  }
  const expertByFlavor = experts[flavor];
  return (quantity) => {
    return `${quantity} ${flavor} candies are made 
                by ${expertByFlavor.name}.`; 
  }
}

// The factory doesn't want to send you their experts,
// Because it may leak their top secret recipe. 
// Instead, they just send you a way to call the expert (as a function) 
// and waiting for your calling to order anytime.
// Now the factory keeps your flavor and your expert.
// In conclusion:
// Only the inner function can access outer function'scope.
// Only the factory can directly tell the expert what to do.
const chocolateExpert = candyFactory('Chocolate');
const stawberryExpert = candyFactory('Strawberry');

console.log(chocolateExpert(1000)); 
// 1000 Chocolate candies are made by Tim.
console.log(stawberryExpert(500));
// 500 Strawberry candies are made by Alex.
Enter fullscreen mode Exit fullscreen mode

Try it at JSFiddle

Comments 16 total

  • Log Boy
    Log BoyFeb 4, 2021

    It's neat, thank you for sharing !

  • Pawan Pawar
    Pawan PawarFeb 4, 2021

    thanks for sharing !

  • Elliot Wong
    Elliot WongFeb 4, 2021

    Nice one Trung. More and more kids are learning how to code, this can come in handy whenever we meet one!

    • Paper Coding
      Paper CodingFeb 4, 2021

      Yeah, it also a way to help us to understand something deeper. Because “If you can't explain it simply, you don't understand it well enough.”
      Albert Einstein

  • 𒎏Wii 🏳️‍⚧️
    𒎏Wii 🏳️‍⚧️Feb 4, 2021

    Not that it matters for the purpose of the article, but I do have to nitpick a bit 😝

    Why are you creating a new experts object with every call of the candyFactory function? That seems like unnecessary work for the garbage-collector.

    Another minor issue is more easily explained with a simple snippet of code:

    console.log(candyFactory('__proto__')(20))
    // 20 __proto__ candies are made 
    //                  by undefined.
    
    Enter fullscreen mode Exit fullscreen mode

    So yea, use new Map() isntead 😉

    • Paper Coding
      Paper CodingFeb 4, 2021

      Yeah we can move the experts out of the function, because it is a constant, and we should validate the input, but it is just a small example, so I took it easy. Thank for your suggestion.

      • lionel-rowe
        lionel-roweFeb 4, 2021

        It may be a little confusing to beginners if the only example given is one where there's no advantage to using a closure (the information-hiding aspect would be better served with a module). Maybe you could expand the article or write a sequel, with a second example that shows off the power and usefulness of closures as a feature.

        • Paper Coding
          Paper CodingFeb 4, 2021

          I am writing the next one, it will be more detailed and it will go with practical examples in real life project and open source. Thank for your suggestion

    • Corentin Girard
      Corentin GirardFeb 4, 2021

      What would your solution for the __proto__ injection be? I didn't understand what you meant about new Map().

    • Ranieri Althoff
      Ranieri AlthoffFeb 5, 2021

      I don't think 5 year-olds are really into __proto__ candies

  • Neth Insta
    Neth InstaFeb 4, 2021

    thank for sharing

  • spartan1cs
    spartan1csFeb 5, 2021

    very neat
    Thanks!!

  • Chapman
    ChapmanFeb 7, 2021

    Sit back and watch the five-year-olds complain about the candy. 😂

  • abasyt
    abasytFeb 8, 2021

    Just ran into this today...

    I just met you,
    And this is crazy,
    but here's my number (delegate)
    So if something happens (event)
    Call me maybe (callback)

    Courtesy LightStriker and kindall on SO

  • Beck Lin
    Beck LinJan 9, 2023

    Thanks for this amazing example !
    I also have another question which might be off the topic here.
    Under what circumstances will we leak the info in the closure ? I mean, if we don't use closure, which means we expose experts in the code, *how could this be unsafe or dangerous *? << I kept thinking about it for a long time

Add comment