A Callback Function Created by a 10-Year-Old
I have a 10-year-old son.
As any parent of a child that age would, I struggled with how to set appropriate screen time limits. After much thought, I came to a conclusion: I decided to incorporate it into his daily study routine. Every day after school, we do some studying together, and once that's done, he gets a coupon that allows him 30 minutes of screen time. The result was a win-win: my son earned screen time that he could enjoy, and I was able to motivate him to study.
One day, while I was doing the dishes, my son came to me and said, "Dad! Let’s play together!!" But I was in the middle of washing dishes, so I replied, "I can’t play with you right now because I’m doing the dishes," and continued with my task. In the meantime, my son used his coupon to watch TV for 30 minutes.
Later, as we were about to go out, he was disappointed and said that he hadn’t been able to play with me. I responded, "But I saw you watching TV after I finished the dishes?" To which he said, "Then tell me when you're done with the dishes."
Oh! Isn’t this exactly the concept of a callback function?
Recommended by LinkedIn
A callback function is a function that is passed as an argument to another function and is executed when a certain condition or event occurs. Let's apply this concept to the situation above.
First, we can define a function to notify the child as notifyChild(), and a function for doing the dishes as doDishes(). Since my son wanted to be notified once I finished the dishes, the doDishes() function should call the notifyChild() function after the dishes are done. Therefore, the doDishes() function needs to accept notifyChild() as a parameter.
Here’s how it would look in JavaScript:
In this code, the doDishes() function calls the notifyChild() callback function after finishing the dishes, just like in the real situation where my son wanted to be informed when I was done.
Callback functions are a useful tool that allow us to automatically link tasks after one is completed. They’re not just for programming but can also be easily applied to everyday life. Just like with my 10-year-old, applying these programming principles to real-life situations can lead to fun and practical ideas.
Great example! I might share the post with the intro to JS course students!!