Sync vs Async (JavaScript)

While learning React there was something important to understand which was synchronous vs asynchronous. I’ve been told by a bunch of peers that this is something important to have a grasp of because of how common it is within JavaScript while creating applications.

Synchronous is when the code is executed from the top of the file and flows downwards hitting each line of code. With asynchronous it will start at the top of the file but when it starts executing, it will then hit an async function, when this happens the code will be executed separately from the rest of the code. It must operate on that function to ensure that it receives what is needed i.e. a promise that will take over a long period of time. In a shorter way of putting it, synchronies will run all code from top to bottom and will always execute in the same exact order. Asynchronous will start at the top and continue until it hits something asynchronous then create threads the more asynchronous functions there are which could lead to code being executed in different orders.

An example of a synchronous file:

Very simple, in the console the results would be the same as the comments that were console.log’d. Everything is being executed in order. Now with some asynchronous code, the example I will be putting down will use a setTimeout function that will hold a console.log for about one hundred milliseconds before executing. Try it out in the console!

Very short and sweet, trying to explain something so complicated for me was a bit of a task but hopefully someone whose reading this who is aspiring to become a programmer will find it helpful. Thank you again for reading this far into my blog, I really appreciate it, remember to drink plenty of water and I'll see ya when you get older!