paint-brush
JavaScript Closures Explained to Kidsby@papercoding22
411 reads
411 reads

JavaScript Closures Explained to Kids

by Paper CodingFebruary 17th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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. 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.
featured image - JavaScript Closures Explained to Kids
Paper Coding HackerNoon profile picture

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.

Try it at JSFiddle