re: Explain Synchronous vs. Asynchronous in JavaScript Like I’m Five VIEW POST

FULL DISCUSSION
 

Here's the 5 year-old's explanation:

Translations to adult language are written like this.

Today, you went to the beach, and you did loads of things like:

  • build a sandcastle
  • go swimming in the sea
  • ask daddy for an ice cream cone
  • go looking for shells
  • eat your ice cream code

You did all of these things one after another, because you can't do multiple things at the same time.
I made a necklace off 5 of the shells you found that you can show off to your friends at school. It has one shell for each of the things you did. Then you can poit at your shells from left to right when telling your friends about the trip, so you don't foret to talk about anything you did.

You can see the thread going through the shells as the **thread of execution. One thing is being done, then the next, then the next, and so on.

After you asked your dad for an ice cream conde, you went looking for shells. You didn't just wait for him to return. And when he came back with the ice cream, he had to wait until you found your last shell before giving you the ice cream.

In JavaScript, asking daddy for ice cream is akin to running some async function, like making an HTTP request. The script continues running after you made the request, running whatever code is left for it to run. When there's no more code to run, JavaScript checks whether there are any events to act upon. When daddy comes back with the ice cream, he puts an event in the event queue, but you're still running the code to search for shells. When you're done, you check if there's anything waiting for you, and you see daddy has returned with a delicious ice cream cone, so you go and eat it.

The JavaScript code for your day at the beach might look like this:

buildSandCastle();
swim();
askDadForIceCream(function(iceCream){
    eatIceCream();
})
findShells();

Even though eatIceCream() comes before findShells() in the code, it only runs at the end, when you've received the event of Daddy returning with the ice cream.

code of conduct - report abuse