DEV Community

loading...
Cover image for How to explain JavaScript Closure to a 5 years old kid

How to explain JavaScript Closure to a 5 years old kid

papercoding22 profile image Trung Nguyen ・1 min read

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

Discussion (15)

Collapse
darkwiiplayer profile image
DarkWiiPlayer • Edited

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 πŸ˜‰

Collapse
rsa profile image
Ranieri Althoff

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

Collapse
papercoding22 profile image
Trung Nguyen Author

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.

Collapse
lionelrowe profile image
lionel-rowe

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.

Thread Thread
papercoding22 profile image
Trung Nguyen Author • Edited

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

Collapse
drarig29 profile image
Corentin Girard

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

Collapse
darkwiiplayer profile image
DarkWiiPlayer

using a Map object instead of a plain JS object avoids the __proto__ problem

Collapse
abasyt profile image
abasyt • Edited

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

Collapse
logboycoding profile image
Log Boy

It's neat, thank you for sharing !

Collapse
aalphaindia profile image
Pawan Pawar

thanks for sharing !

Collapse
spartan1cs profile image
spartan1cs

very neat
Thanks!!

Collapse
e11y0t profile image
Elliot Wong

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

Collapse
papercoding22 profile image
Trung Nguyen Author

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

Collapse
justchapman profile image
Chapman

Sit back and watch the five-year-olds complain about the candy. πŸ˜‚

Collapse
nethinsta profile image
Neth Insta

thank for sharing

Forem Open with the Forem app