Why javascript is synchronous or asynchronous?
Let me start this article by asking, "What is JavaScript"? Well, here's the most confusing yet to-the-point answer I have found so far: Show
JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibility. Hold on a second – did it say single-threaded and asynchronous at the same time? If you understand what single-threaded means, you'll likely mostly associate it with synchronous operations. How can JavaScript be asynchronous, then? In this article, we will learn all about the synchronous and asynchronous parts of JavaScript. You use both in web programming almost daily. If you like to learn from video content as well, this article is also available as a video tutorial here: 🙂 In this article, You'll Learn:
JavaScript Functions are First-Class CitizensIn JavaScript, you can create and modify a function, use it as an argument, return it from another function, and assign it to a variable. All these abilities allow us to use functions everywhere to place a bunch of code logically. Lines of code organized into functions logicallyWe need to tell the JavaScript engine to execute functions by invoking them. It'll look like this:
By default, every line in a function executes sequentially, one line at a time. The same is applicable even when you invoke multiple functions in your code. Again, line by line. Synchronous JavaScript – How the Function Execution Stack WorksSo
what happens when you define a function and then invoke it? The JavaScript engine maintains a
The function execution stack is also known as the Let's look at an example of three functions that execute one by one:
Now let's see what happens with the function execution stack: A step-by-step flow shows the execution orderDid you see what happened there? First, Ok, let's now work through a more complex example. Here is a function
Let's see what's going on with the function execution stack: A step-by-step flow shows the execution orderNotice that first First, The bottom line is that everything that
happens inside the Great! Now that we understand how Asynchronous JavaScript – How Browser APIs and Promises WorkThe word Typically, executing things in sequence works well. But you may sometimes need to fetch data from the server or execute a function with a delay, something you do not anticipate occurring In these circumstances, you may not want the JavaScript engine to halt the execution of the other sequential code. So, the JavaScript engine needs to manage things a bit more efficiently in this case. We can classify most asynchronous JavaScript operations with two primary triggers:
Don't worry if you are new to promises. You do not need to know more than this to follow this article. At the end of the article, I have provided some links so you can start learning promises in the most beginner-friendly way. How to Handle Browser APIs/Web APIsBrowser APIs like
The
Now assume we have a few more lines of code right after the
So, what do we expect to happen here? What do you think the output will be? Will the JavaScript engine wait for 2 seconds to go to the invocation of the
Or will it
manage to keep the callback function of
If you guessed the latter, you're right. That's where the asynchronous mechanism kicks in. How the JavaScript Callback Queue Works (aka Task Queue)JavaScript maintains a queue of callback functions. It is called a callback queue or task queue. A queue data structure is
Whoa, lots of questions! Let's figure out the answers with the help of the following image: The above image shows the regular The JavaScript engine keeps executing the functions in the call stack. As it doesn't put the callback function straight into the stack, there is no question of any code waiting for/blocking execution in the stack. The engine creates a So, the moral of the story is:
Alright, let's see how it works with the code below:
The code executes a So, what do you think the output will be? Here it is:
But, you may think that
Here are steps written out:
I hope it's now clear to you how the How the JavaScript Engine Handles PromisesIn JavaScript, promises are special objects that help you perform asynchronous operations. You can create a promise using the Here is an example of a promise in JavaScript:
After the promise is executed, we can handle the result using the
You use promises every time you use the The point here is that JavaScript engine doesn't use the same What is the Job Queue in JavaScript?Every time a promise occurs in the code, the executor function gets into the job queue. The event loop works, as usual, to look into the queues but gives priority to the The item in the callback queue is called a So the entire flow goes like this:
The image below shows the inclusion of the job queue along with other preexisting items. Now, let's look at an example to understand this sequence better:
In
the above code, we have a If your answer matches this, you are correct:
Now let's see the flow of actions: Callback queue vs. Job queueThe flow is almost
the same as above, but it is crucial to notice how the items from the job queue prioritize the items from the task queue. Also note that it doesn't even matter if the Alright, we have learned everything we need to understand synchronous and asynchronous execution in JavaScript. Here is a Quiz for You!Let's test your understanding by taking a quiz. Guess the output of the following code and apply all the knowledge we have gained so far:
Here is the expected output:
Do you want more such quizzes? Head over to this repository to practice more exercises. In case you are stuck or need any clarifications, my DM is always open on Twitter. In SummaryTo summarize:
Before We End...That's all for now. I hope you've found this article insightful, and that it helps you understand JavaScript's synchronous vs asynchronous concepts better. Let's connect. You can follow me on Twitter(@tapasadhikary), My Youtube channel, and GitHub(atapas). As promised before, here are a few articles you may find useful,
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started Why is JavaScript called asynchronous?Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished.
What is difference between asynchronous and synchronous in JavaScript?Sync is single-thread, so only one operation or program will run at a time. Async is non-blocking, which means it will send multiple requests to a server. Sync is blocking — it will only send the server one request at a time and will wait for that request to be answered by the server.
What do you mean by JavaScript is synchronous?Synchronous JavaScript: As the name suggests synchronous means to be in a sequence, i.e. every statement of the code gets executed one by one. So, basically a statement has to wait for the earlier statement to get executed.
Is JavaScript asynchronous by default?Javascript by default is "synchronous", it's the web APIs that handle "asynchronous" behaviour.
|