Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
History of JavaScript
Next article icon

How JavaScript Works?

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive forms, and many more.

JavaScript, in short JS, was created in 1995 by Brendan Eich, who was working at Netscape Communications. In the beginning, it was designed to add interactivity to websites. Currently, JavaScript can support both client-side and server-side development. It plays a very important role in modern web apps by helping developers manipulate the Document Object Model (DOM), handle user events, and communicate with servers asynchronously.

These are the following topics that we are going to discuss:

Table of Content

  • Evolution of JavaScript
  • JavaScript Engines
  • Execution Contexts in JavaScript
  • Call Stack and Management of Function Calls in JavaScript
  • Asynchronous Tasks and Event Loop in JavaScript
  • Event Loop, Callback Queue, and Microtask Queue
  • Memory Management in JavaScript
  • Call Stack vs. Heap (for function execution)
  • Execution Phases in JavaScript
  • Hoisting in JavaScript
  • Node.js Runtime in JavaScript
  • Concurrency Model in JavaScript
  • Event-Driven Architecture in JavaScript
  • JavaScript’s Prototypal Inheritance
  • How Objects Inherit Properties and Methods in JavaScript
  • JIT Compilation (Just-in-Time Compilation) in JavaScript
  • Modules and Scope in JavaScript
  • Conclusion

Evolution of JavaScript

JavaScript has undergone significant evolution to meet the demands of web development:

  • ECMAScript Standards: JavaScript is based on ECMAScript standards, which define the language syntax, semantics, and libraries. ECMAScript 6 (ES6), released in 2015, it introduced major enhancements such as arrow functions, classes, modules, and promises.
  • Browser Compatibility: Early versions of JavaScript varied between web browsers, which caused compatibility issues. Today, modern browsers and JavaScript engines conform closely to ECMAScript standards, which makes sure the behavior is consistent across different platforms.

JavaScript is an old programming language. Initially, it was quite basic, but as web development needs grew, so did JavaScript. Here are some key updates:

  • ECMAScript 3 (1999): Added useful features like regular expressions for searching text and try/catch for handling errors.
  • ECMAScript 5 (2009): Introduced strict mode to help catch errors and support for JSON (JavaScript Object Notation).
  • ECMAScript 6 (2015): Also known as ES6, it brought major improvements like let and const for variable declaration and arrow functions for cleaner syntax.

There are so many more updates of JavaScript, currently, it is on the 15th edition which is ECMAScript 2024.

JavaScript Engines

JavaScript engines are responsible for executing JavaScript code. The two most important JavaScript engines are V8 (used in Chrome and Node.js) and SpiderMonkey (used in Firefox). These engines follow a similar process to interpret and execute JavaScript:

How JavaScript Engines Interpret and Execute Code?

  • Parsing: When we load a webpage or execute a script, the JavaScript engine first parses the source code to understand its structure. It converts the code into an Abstract Syntax Tree (AST) which is a hierarchical representation of the script.
  • Compilation: Now in compilation phase, the engine translates the AST into machine-readable bytecode using JIT (Just-In-Time) compilation. JIT compilation optimizes performance by compiling frequently executed code segments at runtime.
  • Execution: Finally, the bytecode or machine code is executed line by line, which produces the output or behavior as defined by the JavaScript code.

Example: Here, the engine parses the calculateSum function, compiles it into bytecode or machine code, executes it with arguments 3 and 4, and logs 7 to the console.

JavaScript
function calculateSum(a, b) {     return a + b; }  let result = calculateSum(3, 4); console.log(result); // Output: 7 

Output
7 

Execution Contexts in JavaScript

JavaScript operates within execution contexts, which define the environment in which code is executed. Whenever we run a JavaScript code, a new execution context is created and if there is any proper function call (proper function means not arrow function or variable directly defining and calling a function), the execution context for that function is created inside the execution context of global execution context. If the function returns , the function's execution context is deleted and if there is no more code left, the global execution context is also deleted.

There are two main types of execution contexts:

  • Global Execution Context in JavaScript :The global execution context is the default context in which JavaScript code runs. It includes global variables and functions accessible throughout the script.
  • Function Execution Context in JavaScript :Every time a function is invoked, a new function execution context is created. This context manages local variables, function arguments, and the function's return value.

Call Stack and Management of Function Calls in JavaScript

The call stack is a data structure that tracks function calls in JavaScript. When a function is invoked, its context is pushed onto the call stack. Once the function completes execution, its context is popped off the stack.

The call is stack keeps track the order of execution of execution context.

The call stack contains its first function as the global execution context then if there is a function call , the execution context of that function is pushed inside the stack and if it returns, the call stack pops out the execution context of that function. After completing the whole code execution, the global execution context at bottom of the stack is also popped out which implies the code has been executed.

Example: Here, First () is called and added to the call stack. It again calls second(), which is then added to the stack.Now, second () completes execution and is removed from the stack. First () completes execution and is removed from the stack.

JavaScript
function first() {     console.log("First function");     second(); }  function second() {     console.log("Second function"); }  first(); 

Output
First function Second function 

Asynchronous Tasks and Event Loop in JavaScript

JavaScript is single-threaded, meaning it can only execute one task at a time. It also employs asynchronous programming techniques to handle multiple tasks concurrently without blocking the main thread.

async-in-js
Asynchronous Tasks

Event Loop, Callback Queue, and Microtask Queue

The event loop

Event loop is a mechanism that continuously checks the call stack and manages asynchronous tasks in JavaScript. It ensures that tasks are executed in the correct order and which prevents the main thread from being blocked.

event-loop
event loop in js

Callback queue and microtask queue

It hold tasks which are ready to be executed once the call stack is empty. Promises uses the microtask queue for handling asynchronous operations with higher priority.

Example: The code logs "Start" and "End" immediately since they are synchronous; the promise resolves next due to its microtask priority, logging "Promise," and finally, the setTimeout callback is executed, logging "Timeout," even though it's set to 0ms, as it is placed in the callback queue, which runs after microtasks.

JavaScript
console.log("Start");  setTimeout(() => {     console.log("Timeout"); }, 0);  Promise.resolve().then(() => {     console.log("Promise"); });  console.log("End"); 

Output
Start End Promise Timeout 

Memory Management in JavaScript

JavaScript manages memory allocation in dynamic way to store variables, objects, and functions during runtime.

Allocation of Memory

  • Primitive Values: Stored directly in the stack memory.
  • Objects and Functions: Stored in the heap memory, and references are stored in the stack.

Garbage Collection

JavaScript has automatic garbage collection to get memory occupied by objects that are no longer reachable or referenced by the program. This process helps us to efficiently manage memory and prevent memory leaks.

Example: This example demonstrates the garbage Collection.

JavaScript
let obj = {     name: "John" };  obj = null; // Object is no longer referenced and eligible for garbage collection 

Call Stack vs. Heap (for function execution)

The call stack manages function calls and their contexts, while the heap is used for dynamic memory allocation during runtime.

Call Stack (for function execution)

  • Function Calls: Manages the execution context of function calls in JavaScript.
  • Last In, First Out (LIFO): Operates on a LIFO principle where the most recently called function is processed first.
  • Context Management: Tracks where the execution is in the program with the current function's context.
  • Single Threaded: Executes code sequentially, allowing only one function to be processed at a time.
  • Example: When a function is called (functionA()), its context is pushed onto the call stack. When it completes, its context is popped off, allowing the next function (functionB()) to be processed.

Heap (for function execution)

  • Memory Allocation: Used for dynamic memory allocation during runtime.
  • Objects and References: Stores objects and variables that are accessed globally or referenced from the call stack.
  • Garbage Collection: Managed by the JavaScript engine to reclaim memory occupied by objects that are no longer in use.
  • Example: Objects like arrays or complex data structures (let obj = { key: value }) are stored in the heap. Variables referencing these objects are stored in the call stack.

Execution Phases in JavaScript

JavaScript code execution can be broadly divided into two phases: the Compilation Phase and the Execution Phase.

Compilation Phase:

  • Syntax Analysis: The JavaScript engine parses the source code to understand its structure.
  • Memory Allocation: Allocates memory for variables and functions (hoisting).
  • Example: During compilation, function and variable declarations are processed first, allowing them to be accessed before they are defined in the code (console.log(greet());).

Execution Phase:

  • Code Execution: Executes the compiled code line by line.
  • Evaluation of Expressions: Processes expressions, function calls, and operations defined in the code.
  • Example: After compilation, the engine starts executing from top to bottom, evaluating expressions and performing operations (function greet() { return "Hello"; }).

Hoisting in JavaScript

Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope during the compilation phase. Function declarations '(function greet() { ... })' are fully hoisted, meaning they can be called before they are defined in the code. Variable declarations '(let, const, var)' are hoisted but not their assignments '(let x = 10; hoists let x; but not x = 10;)'.

Example: This demonstrates the hoisting in Javascript.

JavaScript
console.log(greet()); // Output: Hello  function greet() {     return "Hello"; } 

Output:

Hello

Node.js Runtime in JavaScript

Node.js extends JavaScript's capabilities beyond the browser, which enables server-side scripting and development of scalable network applications. It provides built-in modules for file system operations, networking, and HTTP server creation.
Example: This code reads text file in node.js in a file named example.txt and displays in console.

JavaScript
const fs = require('fs');  fs.readFile('example.txt', 'utf8', (err, data) => {     if (err) throw err;     console.log(data); }); 

Concurrency Model in JavaScript

JavaScript uses an event-driven, non-blocking concurrency model to manage multiple tasks concurrently without blocking the main thread.

How JavaScript is Single-Threaded?

JavaScript is single-threaded, meaning it can only execute one piece of code at a time in a single sequence. This single-threaded nature simplifies code execution but poses challenges when dealing with asynchronous tasks like network requests or file handling.

  • Call Stack: JavaScript uses a call stack to keep track of function calls. If a function is currently being executed, it blocks the execution of other functions until it is complete.
  • Event Loop: To manage asynchronous operations, JavaScript uses the event loop. It ensures that even though JavaScript can only handle one task at a time, it doesn't get stuck waiting for long-running tasks like HTTP requests.

Example: Despite the setTimeout being called first, the message is logged last because setTimeout is non-blocking. The call stack clears console.log("Start") and console.log("End") first, then moves to the delayed task.

JavaScript
console.log("Start");  setTimeout(() => {     console.log("Delayed Message"); }, 2000);  console.log("End"); 

Output:

Start
End
Delayed Message

Promises, Async/Await, and Handling Concurrency in JavaScript

Promises and async/await are used to handle asynchronous tasks more effectively, avoiding "callback hell" and making the code more readable.

Promises: Promises represent a value that may be available now, or in the future, or never. They have three states: pending, fulfilled, and rejected.

Example: This example demonstrates the Promises in javascript.

JavaScript
let promise = new Promise((resolve, reject) => {   setTimeout(() => {     resolve("Promise Resolved!");   }, 1000); });  promise.then((message) => {   console.log(message); }); 

Output:

Promise Resolved!

Async/Await: async functions allow you to write asynchronous code that looks synchronous. The await keyword pauses the execution until the promise resolves.

Example: This example demonstrates the usuage of Async/await function.

JavaScript
async function fetchData() {   let data = await fetch("https://api.example.com/data");   console.log("Data fetched:", data); }  fetchData(); 

Event-Driven Architecture in JavaScript

JavaScript is inherently event-driven, meaning actions are taken in response to events such as user interactions, timers, or network responses.

JavaScript's Event-Driven Nature in Web Development

  • Events: Events are actions or occurrences that happen in the system you are programming, such as a user clicking a button or a webpage loading.
  • Event Listeners: Functions that are executed in response to certain events.

Example: When the button with the ID myButton is clicked, the event listener executes the function, logging “Button clicked!”.

JavaScript
document.getElementById("myButton").addEventListener("click", function() {     console.log("Button clicked!"); }); 

Event Delegation and Handling User Interactions

Event delegation is a technique to handle events efficiently by using a single event listener to manage all events of a particular type.

Example: Instead of attaching an event listener to each li element, we attach it to the parent and use event delegation to identify which li was clicked.

JavaScript
document.getElementById("parent").addEventListener("click", function (event) {     if (event.target && event.target.matches("li.item")) {         console.log("List item clicked!");     } }); 

JavaScript’s Prototypal Inheritance

Prototypal inheritance allows objects to inherit properties and methods from other objects, using prototypes.

prototypincalInheritanceInJs
JavaScript’s Prototypal Inheritance

How Objects Inherit Properties and Methods in JavaScript

Prototype Chain: Each object in JavaScript has a prototype object, which acts as a template from which it inherits properties and methods.

Example: This JavaScript code defines a constructor function Person to create person objects with name and age properties, and adds a greet method to the Person prototype to print a greeting message.

JavaScript
function Person(name, age) {     this.name = name;     this.age = age; }  Person.prototype.greet = function () {     console.log("Hello, my name is " + this.name); };  let john = new Person("John", 30); john.greet(); 

Output
Hello, my name is John 

Role of Prototypes in JavaScript

  • Inheritance: Prototypes enable inheritance in JavaScript. An object can use another object's methods and properties through its prototype chain.
  • Shared Methods: Methods defined on the prototype are shared across all instances, saving memory.

JIT Compilation (Just-in-Time Compilation) in JavaScript

JIT compilation is an optimization technique used by modern JavaScript engines to improve performance by compiling code at runtime.

How Modern JavaScript Engines Use JIT for Performance Optimization

  • Parsing and Compilation: Initially, JavaScript code is parsed and compiled to an intermediate bytecode, which is executed by the engine.
  • Dynamic Optimization: The JIT compiler optimizes frequently executed code paths, compiling them to machine code to speed up execution.

Example: The add function, called repeatedly in a loop, may be optimized by the JIT compiler to reduce execution time.

function add(a, b) {
return a + b;
}

for (let i = 0; i < 1000000; i++) {
add(10, 20);
}

Modules and Scope in JavaScript

Modules and scopes in JavaScript help in organizing code, preventing conflicts, and improving maintainability.

Understanding JavaScript Modules (ES6 Modules, CommonJS)

ES6 Modules: Introduced in ES6, they use import and export statements to include or share code between files.

Example:

// In utils.js
export function add(a, b) {
return a + b;
}

// In main.js
import { add } from './utils.js';
console.log(add(10, 20)); // Output: 30

CommonJS: CommonJS modules use require and module.exports for importing and exporting code (commonly used in Node.js).

Example:

// In utils.js
module.exports = {
add: function (a, b) {
return a + b;
}
};

// In main.js
const utils = require('./utils.js');
console.log(utils.add(10, 20)); //Output:30

Global, Function, and Block-Level Scopes

Global Scope: Variables declared outside of functions or blocks are in the global scope, accessible from anywhere in the code.

var globalVar = "I am global";

function showGlobal() {
console.log(globalVar);
}

showGlobal(); //Output: I am Global

Function Scope: Variables declared within a function are only accessible within that function.

function showLocal() {
var localVar = "I am local";
console.log(localVar);
}

showLocal(); // Output: I am local
console.log(localVar); // Error: localVar is not defined

Block Scope: Introduced in ES6, let and const are block-scoped, meaning they are only accessible within the block they are declared in.

if (true) {
let blockVar = "I am block scoped";
console.log(blockVar); // Output: I am block scoped
}
console.log(blockVar); // Error: blockVar is not defined

Conclusion

Understanding these advanced concepts such as concurrency, event-driven architecture, prototypal inheritance, and scopes, helps us to write more efficient and scalable JavaScript code. It allows us to handle asynchronous operations smoothly, utilize inheritance effectively, and organize code through modules and scopes, enhancing both frontend and backend development.


Next Article
History of JavaScript

A

arshihauime
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • JavaScript Hello World
    The JavaScript Hello World program is a simple tradition used by programmers to learn the new syntax of a programming language. It involves displaying the text "Hello, World!" on the screen. This basic exercise helps you understand how to output text and run simple scripts in a new programming envir
    2 min read
  • How closure works in JavaScript ?
    In this article, we will discuss about the closures working JavaScript. Let us first understand what exactly closures are and basic details which are associated with closures in JavaScript. A Closure is a combination of a function enclosed with references to its surrounding state (the lexical enviro
    2 min read
  • History of JavaScript
    Brendan Eich developed JavaScript, a computer language, in just ten days in May 1995. Initially called Mocha, then LiveScript, it finally became known as JavaScript. It was designed for the client-side of websites to add dynamic and interactive elements to static HTML pages. History of JavaScriptJav
    4 min read
  • How to Minify JavaScript
    JavaScript, as a scripting language, plays a fundamental role in modern web development, enabling dynamic and interactive features on websites and web applications. However, as JavaScript files grow in complexity and size, they can significantly impact page load times and overall performance. To mit
    3 min read
  • JavaScript For Loop
    JavaScript for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. [GFGTABS] javascript // for loop begins when x=2 // and runs till x <= 4 for (let x = 2; x <= 4; x++)
    5 min read
  • JavaScript Loops
    Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as long as a specified condition is true. This makes code more concise and efficient. Suppose we want to print 'Hello World' five times. Instead of manually writing the print statement repeatedly, we can
    3 min read
  • JavaScript Operators
    JavaScript operators are symbols or keywords used to perform operations on values and variables. They are the building blocks of JavaScript expressions and can manipulate data in various ways. There are various operators supported by JavaScript. 1. JavaScript Arithmetic OperatorsArithmetic Operators
    5 min read
  • HTML JavaScript
    HTML JavaScript is the most popular programming language that helps to add interactivity and provides dynamic behavior. It is known as the client-side scripting language for web pages. JavaScript is used for various purposes, including DOM manipulation, asynchronous requests (AJAX), event handling,
    2 min read
  • How getElementByID works in JavaScript ?
    The document method getElementById() returns an element object representing the element whose id property matches with the given value. This method is used to manipulate an element on our document & is widely used in web designing to change the value of any particular element or get a particular
    2 min read
  • What is JavaScript?
    JavaScript is a powerful and flexible programming language for the web that is widely used to make websites interactive and dynamic. JavaScript can also able to change or update HTML and CSS dynamically. JavaScript can also run on servers using tools like Node.js, allowing developers to build entire
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences