Image for post

JavaScript Concurrency Model

JavaScript is a single threaded programming language. This means that only one piece of code can run at a time, on a single main thread, and everything else is blocked until an operation completes.

But we don’t want to wait or get blocked for a certain asynchronous task to complete! Imagine scrolling through Instagram and not able to actually scroll until a particular feed is loaded completely. That would be really awful!

Luckily, JavaScript is a non-blocking language, and this article is all about how things work under the hood.

Table of Contents

  1. Execution Context
  2. Call Stack
  3. Task Queue
  4. Job Queue
  5. Event loop — How it all works together!

Execution Context

Before we get into how JavaScript handles asynchronous tasks, one should know how exactly JavaScript code executes.

Execution context_ is an abstract concept that holds information about the environment within which the current code is being executed._

  • Whenever a JavaScript file loads in the browser for the first time, a global execution context is created.
  • Every-time we call/invoke a function, a new execution context gets created.
  • When we return out from a function OR function body is completely executed, the execution context of that function is destroyed and garbage collected.

Basically, 2 things happen(simultaneously) whenever a JavaScript code is executed in a given execution context —

  1. Threading - JavaScript thread executes each line of code one at a time in a procedural manner.
  2. Memory - JavaScript creates new labels and store in memory, all the variable/function declarations for a given execution context

#coding #js #asynchronous #javascript #concurrency #programming

Demystifying Asynchronous JavaScript — Event Loop, Call stack, Task Queue
3.40 GEEK