Hectic JavaScript Interviews Questions!

Is JavaScript Asynchronous or Synchronous? How Does JavaScript Work?

Adiba Abid
Jul 29 · 11 min read
Image for post
Image for post
Photo by Tim Gouw on Unsplash

JavaScript has evolved so much over the years that it’s difficult to categorize. Today, I’m going to dive into whether JavaScript is Synchronous or Asynchronous and what workflow looks like under the hood. And of course, also give you the answer most asking questions in interviews. Let’s jump into the article.

How Does JavaScript Work?

Imagine getting this question during an interview or how about this explain the difference between Asynchronous and synchronous in JavaScript? Or maybe they ask you to explain the statement “JavaScript is a single-threaded language that can be non-blocking!’’ Don’t worry I’m going to help you with those questions in this article.

We don’t need to know How JavaScript works internally to write a program. But NO! It is important to learn. I see a lot of people who have been developers for years and not know this, it’s like being a pilot and not knowing How an Airplane can fly! okay, that’s a little bit dramatic there but you get my point so let’s start first.

What is a Program?

Well, a program has to do some simple things:

Allocate Memory it has to allocate memory otherwise, we wouldn’t be able to have variables or even have a file on our computer.

Parse and Execute — it also has to parse and execute scripts which means read and run commands.

JavaScript V8 Engine
JavaScript V8 Engine
Image Credit- WikiPedia

Now, We also know that there’s the JavaScript Engine each browser implements in chrome is the V8 and V8 Engine reads the JavaScript that we write in changes into machine-executable instructions for the browser now the engine consists of two parts a Memory Heap and a Call Stack.

Now the Memory Heap, This is where the memory allocation happens and then the Call Stack is where the code is read and executed it tells you where you are in the program so let’s simplify this and show you what I mean.

When declaring a variable, JavaScript will automatically allocate the memory for the variables.

const a = 100; //allocate memory
const b = 10;
const c = 1; //allocate memory

We’ve just Allocated memory now when we assign this the javascript engine is going to remember that oh yeah a has a value of one hundred. We’ve just used up the Memory Heap and I can keep going, I can keep copying and pasting and changing these variables to B and C and I can change the values too. now that’s an issue that we see with this there’s something called a Memory Leak that you’re gonna hear as you become a developer and what we’ve done here is we’ve created all these variables Global Variables that are in the Memory Heap.

Imagine if I had just this page full of variables and instead of just numbers they’re like very big arrays well, memory leaks happen. When you have unused memory such as let’s say we’re not using the variable A but it’s Global well by having unused memory just laying around, it fills up this Memory Heap and that’s why you might hear why Global Variables are Bad.

Global variables are bad because if we don’t forget to clean up after ourselves we fill up this memory heap and eventually, the browser will not be able to work all right. So that’s Memory Allocation.

Image for post
Image for post
Memory Heap and Call Stack (Photo by- Unsplash)

let’s talk about the Call Stack what is that well again with a call stack we can have something like this:

//CALL STACK
console.log(“1”);
console.log(“2”);
console.log(“3”);
Call Stack Example
Call Stack Example
Call Stack Example

Console.log will go one, Console.log two, and then finally Console.log three. If I run this code in my browser terminal well I get one two three. If you remember that’s what the Call stack does? It reads and executes our Scripts.

Let’s Run step by step:

  • It reads the first line console.log it gets put in this call stack, and then it runs it and creates 1.
  • Then it says okay I’m removing the first console.log because I just finished running it. I’m gonna place the second console.log into my call stack. Adds it on here and says yes execute and then it removes that it and pops it.
  • Then gets console.log 3 and logs console log three and then finally removes.

Synchronous JavaScript

JavaScript is a Single-Threaded Language that can be non-blocking.

JavaScript is a Single-Threaded language that can be non-blocking. Single-threaded means that it has only one Call Stack and one call stack only do one thing at a time mean Synchronous and as you saw a call stack is First in Last Out so, whatever’s at the top of the call stack gets run first then below that, and below that, until the call stack is empty now other languages can have Multiple Call Stacks and those are called Multi-Thread.

You can also see how that might be beneficial to have multiple call stacks so that we don’t keep waiting around for stuff. Then Why was JavaScript designed to be Single-Threaded?

Well, running code on a Single-Thread can be quite easy since you don’t have to deal with complicated scenarios that arise in a Multi-Threaded Environment.

Now, you may have heard of the site Stack Overflow. If you’re a developer you use it on a daily basis and have you ever wondered what stack overflow means? Well, stack overflow is this:

Call stack Overflow
Call stack Overflow
Call Stack OverFlow

When a step is overflowing, kind of like we talked about Memory Leaks and How the Memory heap of a JavaScript engine can overflow! well with stack overflow this happens when the call stacks just get bigger and bigger and bigger until it just doesn’t have enough space anymore.

How can we do that? Can we recreate a stack overflow? yeah, I can show you quickly that to create a function foo as we have in here and this function will just have foo and we’re just gonna run our foo function alright that looks confusing but what is happening here? This is something called Recursion.

Recursion function
Recursion function
Recursion example

Recursion means a function that calls itself so if you look at what this function do we run foo and foo gets executed. What foo had does is? We run through again so it just keeps looping over and over again having a recursion but there’s no end in sight right? We keep adding foo to the call stack, we keep adding it over and over and so on…

We have a stack overflow so if you want to have fun go into your browser go into your console and run something like this and see what happens you’re gonna get a stack overflow.

Alright so hopefully, this now makes sense the JavaScript Engine V8 and Chrome has a Memory Heap and a Call Stack.

Now JavaScript is single-threaded only one statement is executed at a time but there is a problem, now isn’t it what if line 2 of console.log was a big task we needed to do maybe loop through an array that had millions of items. What would happen there?

JavaScript is a Single threaded language.
JavaScript is a Single threaded language.
Synchronous Example

Well, with Synchronous Tasks if we have one function that takes up a lot of time it’s going to hold up the line.

Example:

Imagine a buffet restaurant, If all the people want to eat but Bobby says, hold on guys I have to keep eating and putting bacon on my plate well everybody has to wait in line so, sounds like we need something non-blocking. Remember our first statement that we made in this article? JavaScript is a Single-Threaded Language that can be non-blocking. Ideally, we don’t wait around for things that take time so how do we do this?

Well, Asynchronous to the rescue. We need something more than just Synchronous Tasks. You’re thinking to yourself, How do we do Asynchronous programming tasks?

Asynchronous Example
Asynchronous Example
Asynchronous Example

Well, we can do Asynchronous Programming by doing something like this, setTimeout which we’re going to talk about is a function that comes within our browsers and it allows us to create a Timeout and we can just give it the first parameter is the function that we want to run and then the second parameter is how many seconds we want to wait so, let’s say I want to wait two seconds so 200 minutes 2,000 milliseconds. If I do this now let’s run into the console and see what happens. Try yourself too to see what happens.

Image for post
Image for post
Asynchronous Example Result

Well, what just happened? we have console.log one then console.log 3 and then console.log 2. After 2 seconds later it looks like we just skipped this whole step and then put this at the very end well you’ve just witnessed Asynchronous Programming.

JavaScript runtime environment. JIT Compiler
JavaScript runtime environment. JIT Compiler
JavaScript Runtime Environment

In order to understand this and what just happened, I need to take you to the next part and that is in order for JavaScript as we know it to run for the JavaScript engine with Memory heap and Call stack to run. We need more than just The JavaScript engine, we need what we call a JavaScript Runtime Environment.

The JavaScript Runtime Environment is part of the browser, it’s included in the browser’s. They have extra things, On top of the Engine, they have something called Web APIs, Callback Queue, and an Event Loop.

As you can see here, Set Timeout is part of the Web API it’s not technically part of JavaScript, is it? It’s what the browser’s give us to use so, we can do the Asynchronous programs.

Okay so looking at this diagram let’s see if we can figure out what our code was doing.

JavaScript Run time Environment, Set Timeout()
JavaScript Run time Environment, Set Timeout()
JavaScript Run Time Environment step by step Example.

We can create here our own call stack, We’ll have Web API, then we’ll have a Callback queue and an Event loop. Just like we have in our JavaScript runtime environment so what’s happening here:

  • Well first we have console.log that goes into the call stack and that gets run so we log console.log to the browser.
  • We then get Set Timeout into our call stack because we finish this first task we’re going to the second one, And what set timeout what’s gonna happen is? Well if the call stack is gonna say okay a half set timeout and because the set timeout is not part of JavaScript but part of the Web API it has this special characteristic what’s gonna happen is it triggers the Web API and says that Set Timeout has just been caught and because we notified a Web API, we can pop it out of the call stack.
  • Now the web API starts a timer here a timer of two seconds but it’s gonna know that in two seconds you have to do something and because the call stack is empty the JavaScript engine now goes to console.log 3. And executes this so that makes sense right now we’ve done 1 and 3 but we still have set timeout to seconds in the web API.
Callback function
Callback function
Callback function.
  • Now after 2 seconds when our time limit is up, The Web API is gonna say ok SetTimeout should be run let’s see what’s inside of it well we have console.log, so what’s going to happen is?It’s going to say hey set timeout is done we have a callback and this callback of setTimeout we added to the callback queue saying that hey we have to run something we’re ready to Run It.
  • The last part the Event Loop over here checks and says hey is the call stack empty and it keeps checking all the time. If the stack is empty and there’s nothing running right now on the JavaScript engine it’s going to say, Hey do we have any callbacks? it’s gonna check the callback queue and say, Hmm is anything in there because the call stack is empty we can throw something in there and make it do some work in our case we say, oh yeah I do let me put this into the call stack so now we move the callback into the call stack and then the callback we run it and by running we see that we have console.log.
  • So it’s going to say console.log, it’s going to run this function and once it’s done it’s going to pop it out of the call stack and again we’re done with the callback so we remove it and there you go, We’re done everything is empty and we’ve just run this Example, it’s gonna go through the entire Web API Callback Queue, Event loop.

Wooh! There’s was a lot of information but hopefully, that makes sense to you of Why we noticed this behavior and I want to challenge your understanding here knowing what you know and what I just taught you what happens if I change this setTimeout to zero? that means zero seconds I’m going to give you a second to think about what will happen.? And Answer yourself.

Now, In the end, If you’re able to understand this Article. You’ll actually have a lot of people that, Hire for JavaScript roles asking questions like this in an interview and you have to explain why that is? so, I hope that makes sense to you and you can use that to your advantage in the next interview.

I’ll give you an example to understand it more better. Imagine calling your teacher with a question:

The Synchronous way is you call the teacher you wait on the phone until the Teacher answers the phone and ask him the question and hopefully get an answer so, You let the phone ring until he picks up but you’re not doing anything else in the meantime.

The Asynchronous way means you send a text to a teacher with a question and then when the teacher he or she has the time will respond to you and call you with the answer so, You can do other stuff in between.

So JavaScript is Asynchronous when you can leave it a message and a call back tells you, Hey Mr. the teacher has a message for you when you’re not too busy. And that’s why we call it a callback function in a callback queue we’re calling back to let them know that hey there’s some stuff waiting for you now we see over here.

Let’s recap:

What we just learned? JavaScript is a single-threaded language that can be non-blocking. It has one Call Stack and it does one thing at a time.

In order to not block the Single-thread, it can be Asynchronous with Callback Functions and these callback functions get to run in the background through the Callback queue and then the Event Loop to bring it back into the Call Stack. So, the next time you get asked about these topics, you should have a little bit more confidence to answer that question.

I hope that this was helpful!

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Adiba Abid

Written by

Web Developer — Tech Enthusiast | Creative mind | Explorer| Learner| Nature Lover | Entrepreneur | ‘’Working on Myself, By Myself, For Myself’’ —Stay Positive.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Adiba Abid

Written by

Web Developer — Tech Enthusiast | Creative mind | Explorer| Learner| Nature Lover | Entrepreneur | ‘’Working on Myself, By Myself, For Myself’’ —Stay Positive.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store