Explain Callback Like I'm Five

Did you find this post useful? Show some love!

Callbacks are friends we send along inside functions to help accomplish additional tasks.

I'm going to send you to the store with money to get groceries. But I need to know how you're doing at the store. So I'm also going to send your friend, and he'll call back home and let me know how things are going. I might even ask him to do other things for me, like drive you home with the groceries.


function getGroceries(shoppingList, friend) {

    this.purchase(shoppingList)

    if(friend)
    {
        friend(this.purchase)
    }

    return this.purchase

}

function friend(purchase) {
    console.log(`Hey mom, we bought everything. Here's the reciept`)
    console.log(purchase)
}

const shoppingList = [ 'apples', 'carrots', 'chips' ]

getGroceries(shoppingList, friend)

Sometimes, you need friends to do certain things, like setting a timeout (as exhibited by @nestedsoftware ). That's a 2-person job, someone to set the time and someone to actually do something.

A callback is a function that you pass in as a variable to another function. A typical example in JavaScript is the setTimeout function. If you want something to execute after a delay, you can pass it as a callback to setTimeout.

function sayHello() {
    console.log('Hello there!');
}

setTimeout(sayHello, 1000);

setTimeout will wait 1 second (1000 milliseconds) and then it will actually call sayHello. The result is that "Hello there!" will get printed to the console after one second.

Because it takes a function as an argument, setTimeout is called a "higher order function."

Classic DEV Post from Jul 7

Lay Out Your Code Like You'd Lay Out Your House

Laying out your code base optimally can have a big impact on how easy it is to understand and maintain.

READ POST
Follow @_bigblind to see more of their posts in your feed.
dev.to is now open source!
View Announcement Post View GitHub Repo
RupeshGoud
A Computer Science Nerd !!
Trending on dev.to
Gist Interview - Programming questions simulator
#react #githubgist #javascript #showdev
How Web APIs work?
#beginners #webapi #javascript #html
Explain Grunt Task Runner Like I'm Five
#explainlikeimfive #javascript #discuss
Front End Development Automation with Puppeteer. Part 3
#webdev #automation #node #javascript
Playing with Discrete Fourier Transform Algorithm in JavaScript
#javascript #algorithms #computerscience #programming
Opensource Repository for All Experience
#beginners #opensource #javascript #webdev
Fighting boredom with a HyperApp experiment
#javascript #hyperapp #react #vue
Read This Before Starting a Bootcamp
#beginners #learning #programming #career