Why does Javascript seem to have asynchronous execution?

Javascript is a synchronous, interpreted and dynamically typed programming language that is generally used to make browsers/html more interactive. When I first learned this, I was a little confused to say the least. How is Javascript synchronous? Doesn’t Javascript allow the user to click multiple things at once and execute all of them together? Initially I was sure that there must’ve been a mistake in what I was reading, but further research revealed to me that Javascript was in fact synchronous. So what gives? I looked into it further and while the results were surprising to me, it was also very informative.

The way Javascript (and most other programming languages) work is that they have something called an execution stack. The execution stack can be thought of as the stack that contains all the functions that you call (this is also the reason that when you call too many functions in recursion the error is referred to as a stack overflow as the execution stack literally ran out of memory to store your function calls). Here is an illustration of the execution stack along with with model javascript code corresponding to it.

While the execution stack is common to most programming languages and Javascript’s execution stack works very similarly to most other ones, there is another underlying data structure that gives Javascript (at least the feeling of) its asynchronous execution. The event queue is what provides this functionality. The event queue is what the rest of the browser uses to communicate with the Javascript interpreter. When you click something in the browser, that event gets put on the event queue. The browser communicates with the javascript engine to put it on the event queue. However, Javascript is still synchronous, so even though that event is ON the event queue, it will only get executed after the execution stack is empty. In other words, Javascript keeps events on the event queue and once all the items on the execution stack have been popped off, it looks at the event queue and checks if there are instructions within the code (left by the programmer) on what to do for specific events. These are usually called asynchronous call backs and while they do work asynchronously, Javascript in and of itself is synchronous and executes lines one by one. The process of putting events on the event queue is asynchronous as multiple events can be occurring at once (for example an HTTP request as well as pressing a button), however, Javascript will only ever deal with events one at a time and execute their code line by line.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.