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 ...
For further actions, you may consider blocking this person and/or reporting abuse
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 thecandyFactory
function? That seems like unnecessary work for the garbage-collector.Another minor issue is more easily explained with a simple snippet of code:
So yea, use
new Map()
isntead 😉I don't think 5 year-olds are really into
__proto__
candiesYeah we can move the
experts
out of the function, because it is aconstant
, and we should validate the input, but it is just a small example, so I took it easy. Thank for your suggestion.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.
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
What would your solution for the
__proto__
injection be? I didn't understand what you meant aboutnew Map()
.using a
Map
object instead of a plain JS object avoids the__proto__
problemJust 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
It's neat, thank you for sharing !
thanks for sharing !
Nice one Trung. More and more kids are learning how to code, this can come in handy whenever we meet one!
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
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
very neat
Thanks!!
thank for sharing
Sit back and watch the five-year-olds complain about the candy. 😂