Skip to main content

Command Palette

Search for a command to run...

How JavaScript Works Behind the Scenes – A Beginner’s Guide

Updated
4 min read
How JavaScript Works Behind the Scenes – A Beginner’s Guide

INTRODUCTION

The web's language is called JavaScript. Everything from dynamic content to sophisticated web applications is powered by it. However, have you ever pondered the inner workings of JavaScript? Why is it so quick, asynchronous, and single-threaded?

We'll reveal everything in this blog, from the engine to the event loop, in the most straightforward manner imaginable.

1. What is JavaScript?

JavaScript is a single-threaded, interpreted, high-level programming language. It enables websites to become interactive and operates within your browser, such as Chrome or Firefox. Consider JavaScript magic in the form of sliders, pop-ups, animations, and form validations.

2.The Fundamental JavaScript Engine

A program that runs JavaScript code is called a JavaScript engine.

Each browser has a unique engine.

  • V8 (Node.js, Google Chrome)

  • Firefox's SpiderMonkey

  • Safari's JavaScriptCore

  • Chakra (Microsoft Edge Legacy)

    Since V8 is the most well-liked and frequently utilized, we'll concentrate on it.

    V8 Engine Components:

    1.Memory Heap

  • Where memory allocation takes place.

  • And holds the definitions of functions, variables, and objects.

    2.The Call Stack

  • Controls the invocation of functions.

  • Adheres to the Last-In-First-Out (LIFO) principle.

3.Javascript Code Execution

Suppose you write the following code:

function greet() {
    console.log("Hi!");
}
greet();

Behind-the-scenes activities:

The code is parsed by the JavaScript engine. It creates a Global Execution Context.

  • Memory is set aside for functions and variables.

  • The Call Stack receives a push of greet().

  • Console.log("Hi!") is pushed and run.

  • When a function is finished, it is removed from the stack.

4.The Environment as an Execution Context

An Execution Context is created by JavaScript when code is executed, and it includes:

  • The environment in which variables and functions reside is known as the variable environment.

  • For addressing variable access, use the scope chain.

  • This depends on how a function is called.

Execution Context Types:

It has two types.

1.When the script starts, the global execution context is created.

2.Every time a function is called, a functional execution context is created.

5.JavaScript Memory Management

Memory Heap:

  • A sizable, unstructured area of memory used to store items.

Garbage Collection:

  • JavaScript manages memory automatically.

  • Memory used by items that are no longer in use is released by the garbage collector.

  • V8 cleans up unused memory using the Mark-and-Sweep Algorithm.

6.Single-Threaded Nature of JavaScript

JavaScript manages memory automatically. Memory used by items that are no longer in use is released by the garbage collector.V8 cleans up unused memory using the Mark-and-Sweep Algorithm. it's nature Because JavaScript is single-threaded, it can only perform one action at a time. The Call Stack is used to run all code on a single main thread.

However, how does JavaScript manage asynchronous processes like setTimeout, DOM events, and API calls if it is only single-threaded?

Let's examine that in the following section.

7.Web APIs: The Toolbox of the Browser

The browser environment's Web APIs, which are not a component of JavaScript itself, are accessible to JavaScript in the browser.

Web examples:

  • setTimeout()

  • DOM manipulation

  • fetch()

  • Event listeners

    To prevent the main thread from being blocked, these tasks are assigned to the browser.

8.Task Queue & Callback Queue

Web APIs pass the callback function to the Callback Queue (also called the Task Queue) when their task is finished, such as after two seconds in setTimeout().

9.The Traffic Controller's Event Loop

The Call Stack and the Callback Queue are continuously observed by the Event Loop.

How it operates:

The Event Loop pushes the first callback from the Callback Queue to the Call Stack so that it can be executed if the Call Stack is empty.

Example:

console.log("Start");

setTimeout(() => {
  console.log("Inside Timeout");
}, 1000);

console.log("End");

Output:

Start
End
Inside Timeout

Why?

The Web API handles setTimeout() → Callback goes to the Callback Queue after 1000 ms, and the Event Loop only sends it to the Call Stack when it is empty.

10.Advanced Microtasks vs. Macrotasks

There are two kinds of task queues in JavaScript:

  • Macrotask Queue: for setTimeout, setInterval, setImmediate, and I/O tasks.

  • Microtask Queue: for MutationObserver, queueMicrotask, and Promises.

Prioritized and completed immediately following the current task, microtasks come before macrotasks.

11.Flow Diagram

Your Code
   ↓
JavaScript Engine (Parsing)
   ↓
Memory Allocation → Execution Context Created
   ↓
Call Stack (Function Execution)
   ↓
Web APIs (for async tasks)
   ↓
Callback Queue (waiting)
   ↓
Event Loop (checks if Call Stack is empty)
   ↓
Callback pushed to Call Stack → Executed

CONCLUSION

Although JavaScript appears to be a straightforward scripting language, it is actually a sophisticated, well-coordinated system that uses the JavaScript engine, event loop, call stack, and browser APIs to manage both synchronous and asynchronous tasks.

Debugging, performance optimization , and writing better code all depend on an understanding of this inner working.

More from this blog

Untitled Publication

15 posts