Introduction to Sync Async Programming

Overview

JavaScript is a single-threaded programming language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing piece of code before moving into the next. However, thanks to the V8 engine, JavaScript can be asynchronous which means we can execute multiple tasks in our code at one time.

Synchronous JavaScript

Synchronous code in JavaScript will start from the top of a file and execute all the way to the bottom, each line in order until it gets the bottom and it will stop. For example, if a function takes a while to execute or has to wait on something, it freezes everything up in the meanwhile because synchronous code in JavaScript can only do one task at a time, it waits until a particular statement has executed then it moves to the next one. A good example of this happening is the window alert function alert("hello world"):

window.alert("Hi");

You can't interact with the webpage at all until you hit OK and dismiss the alert.

Asynchronous JavaScript

We mentioned above that JavaScript is a single-threaded language, So how do we get asynchronous code with JavaScript then?

Well, the JavaScript engine has a web API that handles tasks in the background. The call stack recognizes functions of the web API and hands them off to the handled by the browser. Once those tasks are finished by the browser, they return and pushed onto the stack as a callback. That can help execute multiple functions at one time,