Javascript — Synchronous versus Asynchronous

As a software engineer, one concept you need to understand is the difference between synchronous and asynchronous code. As the name implies, synchronous code is sequential, or one at a time. Each line of code is dependent on the completion of the previous line above and doesn’t get performed until the prior is finished. As you may have guess, Javascript is inherently synchronous.

Let take a look at a quick sample of of synchronous code in Javascript.

Since Javascript is always synchronous, when we run each line of code, the output would follow sequential like above. If there was an error or bug in one of the lines (lets say line two where we are logging “One”), then our code would stop and error out at line two. The remaining of the logs ( Two, Three, Four) would not post on to the console until our line two is fixed and completed.

If we are running an application, we don’t want a synchronous display of our code. In case there is a minor bug in our application, we still want the rest of our application to function. How do we make our application asynchronous?

We call upon functions! In Javascript we have to remember that functions are first class citizens (objects). This means that regardless of what is being run before, a function running doesn’t depend on the completion of that prior code. The function will execute regardless if there is an error or not.

We will use one of the most popular examples of the builtin in Javascript set timeout function to demonstrate asynchronous code.

Set timeout is a builtin Javascript function that allows you delay the execution of its content by a certain amount of time. Here we are telling it to console log Two after 5 seconds. As you can see since the function is asynchronous, our console will return One, then Three. It will not wait the full five seconds for our set time out function to finish. If you open your console and your browser, you can test this out and see the console print Two after 5 seconds.

So we went from synchronous to asynchronous. You may think, is there a way make a (asynchronous) function synchronous? Yes, and in order to do so we will use the infamous callback functions in Javascript. By implementing a callback in to a function, the original function will not run until the callback function within is complete. To learn more about callbacks, promises and async await, you can read more on W3Schools website.

Software Engineer