DEV Community

Discussion on: How to explain JavaScript Closure to a 5 years old kid

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • 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
 
papercoding22 profile image
Paper Coding

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
Paper Coding • 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
𒎏Wii 🏳️‍⚧️

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

Collapse
 
rsa profile image
Ranieri Althoff

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