An Interest In:
Web News this Week
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
- March 25, 2024
- March 24, 2024
- March 23, 2024
February 4, 2021 07:36 am GMT
Original Link: https://dev.to/papercoding22/how-to-explain-javascript-closure-to-a-5-years-old-kid-4d6n
How to explain JavaScript Closure to a 5 years old kid
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 a expert 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 send you the expert,// Because it may leak their top secret recipe. // Instead,it just send you a way to call the expert (as a function)// to you 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
Original Link: https://dev.to/papercoding22/how-to-explain-javascript-closure-to-a-5-years-old-kid-4d6n
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To