Open In App

DSA in JavaScript

Last Updated : 10 Oct, 2025
Comments
Improve
Suggest changes
48 Likes
Like
Report

This beginner-friendly guide covers Data Structures and Algorithms (DSA) in JavaScript, including built-in structures like arrays, strings, Map, Set, and user-defined structures such as linked lists, stacks, queues, trees, heaps, and graphs. It also explains how to analyse algorithm efficiency in terms of time and space complexity.

It is recommended to read about Analysis of Algorithms before beginning this tutorial.

Array

Array is a special type of object used to store multiple values in a single variable. Arrays are dynamic, meaning their size can grow or shrink automatically as elements are added or removed.

javascript_array-

Arrays allow storing multiple values of any data type in a single variable, accessible by an index.

JavaScript
let arr = [10, 20, 30, 40, 50];
console.log(arr); 

Related Posts:

Recommended DSA Problems:

Searching Algorithms

A searching algorithm is a method to find a specific element in a data structure like array or list. It checks elements one by one or using a faster approach until the target is found.

JavaScript
// Array of numbers (must be sorted for binary search)
const list = [2, 4, 6, 8, 10];
const key = 6;

//Linear Search
const linearFound = list.includes(key);

// true or false
console.log("Linear Search:", linearFound); 

// Binary Search
function binarySearch(arr, key) {
  let start = 0;
  let end = arr.length - 1;

  while (start <= end) {
    const mid = Math.floor((start + end) / 2);

    if (arr[mid] === key) {
        
    // return index if found
      return mid; 
    } else if (arr[mid] < key) {
      start = mid + 1;
    } else {
      end = mid - 1;
    }
  }

// not found
  return -1; 
}

const index = binarySearch(list, key);
if (index >= 0) {
  console.log("Element found at index", index);
} else {
  console.log("Element not found");
}

Output
Linear Search: true
Element found at index 2

Related Posts:

Recommended DSA Problems:

Sorting Algorithms

Sorting arranges elements in ascending or descending order. JavaScript provides a built-in method sort() to sort arrays. You can also implement common sorting algorithms like Bubble Sort, QuickSort, and MergeSort.

JavaScript
// Array
let nums = [5, 3, 8, 1];

// Sorting array in-place using sort()
nums.sort((a, b) => a - b);
console.log("Sorted array using sort():", nums);


// List (same as array in JS)
let list = [5, 3, 8, 1];

// Using toSorted() on list
let listSorted = list.toSorted((a, b) => a - b);
console.log("Sorted list using toSorted():", listSorted);

Output
Sorted array using sort(): [ 1, 3, 5, 8 ]
Sorted list using toSorted(): [ 1, 3, 5, 8 ]

Related Posts:

Recommended DSA Problems:

String

In JavaScript, a string is a sequence of characters used for text. There’s no separate character type, and like Java and Python, strings are immutable, so any modification creates a new string.

JavaScript
// Immutable string
let s = "Hello Geeks";

console.log(s);

// Strings are immutable, so concatenation creates 
// a new string
let newS = s + " Welcome";

console.log(newS);

// Mutable alternative: using array or 
// StringBuilder-like behavior
// JS doesn't have StringBuilder, 
// but we can use an array and join
let sb = ["Hello"];
sb.push(" Geeks"); 

console.log(sb.join("")); 

// Another modern approach: using template literals
let name = "Geeks";
let greeting = `Hello ${name}`;

console.log(greeting);

Output
Hello Geeks
Hello Geeks Welcome
Hello Geeks
Hello Geeks

Related Posts:

Recommended DSA Problems:

Set

A Set in JavaScript is a collection of unique values.

  • Duplicate values are automatically ignored.
  • Can store any type: numbers, strings, objects, etc.
  • The order of elements is insertion order.
JavaScript
// using an array
let s1 = new Set([10, 30, 30, 40, 40]);
console.log(s1);
let s2 = new Set(["gfg", "gfg", "geeks"]);
console.log(s2);

// using string
let s3 = new Set("fooooooood");
console.log(s3);

// an empty set
let s4 = new Set();
console.log(s4);

Output
Set(3) { 10, 30, 40 }
Set(2) { 'gfg', 'geeks' }
Set(3) { 'f', 'o', 'd' }
Set(0) {}

Related Posts:

Recommended DSA Problems:

Map 

A Map in JavaScript is a collection of key-value pairs where:

  • Keys can be of any type (numbers, strings, objects, etc.).
  • Values can be of any type.
  • The insertion order of elements is preserved.
  • It provides efficient methods to add, retrieve, delete, and check elements.
JavaScript
// Create an empty Map
let myMap = new Map();

// Insert / Add elements
myMap.set('name', 'GFG');
myMap.set('age', 30);
myMap.set('city', 'Noida');

console.log("Initial Map:", myMap);

// Update a value
myMap.set('age', 31);  // updates age
console.log("After update:", myMap);

// Check if a key exists
console.log("Has 'city' key?", myMap.has('city')); // true

// Get a value
console.log("Name:", myMap.get('name')); // GFG

// Delete a key
myMap.delete('city');
console.log("After delete 'city':", myMap);

// Get size of the Map
console.log("Map size:", myMap.size);

// Iterate over Map
console.log("Iterating Map:");
myMap.forEach((value, key) => {
    console.log(key, "=>", value);
});

// Using Map with initial values
let anotherMap = new Map([
    ['name', 'GFG'],
    ['age', 30],
    ['city', 'Noida']
]);
console.log("Another Map:", anotherMap);

Output
Initial Map: Map(3) { 'name' => 'GFG', 'age' => 30, 'city' => 'Noida' }
After update: Map(3) { 'name' => 'GFG', 'age' => 31, 'city' => 'Noida' }
Has 'city' key? true
Name: GFG
After delete 'city': Map...

Related Posts:

Recommended DSA Problems:

Recursion

Recursion is a process in which a function calls itself as a subroutine. This allows the function to be repeated several times, as it can call itself during its execution. Recursion is often used to solve problems that can be broken down into smaller, similar subproblems.

JavaScript
function factorial(n) {
    
  // Base case: if n is 0 or 1, return 1
  if (n === 0 || n === 1) {
    return 1;
  }

  // Recursive case: n! = n * (n-1)!
  return n * factorial(n - 1);
}

console.log(factorial(5)); 

Output
120

Related Posts:

Recommended DSA Problems:

Queue

A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. Elements are inserted at the rear and removed from the front.

JavaScript
// Import the Denque library
const Denque = require("denque");

// Create a queue
const queue = new Denque();

// Enqueue elements at the end of the queue
queue.push("g");
queue.push("f");
queue.push("g");

console.log("Initial queue:", queue.toArray());

// Dequeue element from the front of the queue
// Removes and returns the first element
console.log("Dequeued:", queue.shift());

// Display queue after removal
console.log("Queue after dequeue:", queue.toArray());

Output
Initial queue: [ 'g', 'f', 'g' ]
Dequeued: g
Queue after dequeue: [ 'f', 'g' ]

Related Posts:

Recommended DSA Problems:

Stack

A Stack is a linear data structure that follows LIFO (Last In, First Out)-the element added last is the first to be removed. In JavaScript, there’s no built-in Stack class, but you can easily implement one using arrays or linked lists.

JavaScript
// Create an empty stack
let stack = [];

// push() to add elements
stack.push("a");
stack.push("b");
stack.push("c");

console.log("Initial stack:");
console.log(stack);

// pop() to remove elements (LIFO)
console.log("\nElements popped from stack:");
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.pop());

// Stack is now empty
console.log("\nStack after elements are popped:");
console.log(stack);

// Uncommenting the line below will return undefined since
// stack is empty
// console.log(stack.pop());

Output
30
30
2
false
[ 10, 20 ]

Related Posts:

Recommended DSA Problems:

Linked List

A Linked List is a linear data structure where each element (node) contains data and a reference to the next node.

Linked-list
  • Data Structure: Non-contiguous
  • Memory Allocation: Typically allocated one by one to individual elements
  • Insertion/Deletion: Efficient
  • Access: Sequential
JavaScript
// constructor to initialize a new node with data
class Node {
    constructor(new_data) {
        this.data = new_data;
        this.next = null;
    }
}

// Create the first node (head of the list)
let head = new Node(15);

// Link the second node
head.next = new Node(3);

// Link the third node
head.next.next = new Node(17);

// Link the fourth node
head.next.next.next = new Node(90);

// printing linked list
let temp = head;
while (temp !== null) {
    process.stdout.write(temp.data + " ");
    temp = temp.next;
}

Output
10 20 30 40 

Related Posts:

Recommended DSA Problems:

Tree

A Tree is a hierarchical data structure with nodes connected by edges. The top node is the root.

JavaScript
//Node Structure
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function inOrder(node, res) {
    if (node === null)
        return;

    // Traverse the left subtree first
    inOrder(node.left, res);

    // Visit the current node
    res.push(node.data);

    // Traverse the right subtree last
    inOrder(node.right, res);
}

//Driver Code
// Create binary tree
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(6);

const res = [];
inOrder(root, res);

console.log(res.join(' '));

Output
4 2 5 1 3 6

Related Posts:

Recommended DSA Problems:

Heap

A Heap is a special Tree-based Data Structure that has the following properties.

JavaScript
// JavaScript code to depict
// the implementation of a max heap.

class MaxHeap {
    constructor(maxSize) {
        
        // the array in the heap.
        this.arr = new Array(maxSize).fill(null);

        // Maximum possible size of
        // the Max Heap.
        this.maxSize = maxSize;

        // Number of elements in the
        // Max heap currently.
        this.heapSize = 0;
    }

    // Heapifies a sub-tree taking the
    // given index as the root.
    MaxHeapify(i) {
        const l = this.lChild(i);
        const r = this.rChild(i);
        let largest = i;
        if (l < this.heapSize && this.arr[l] > this.arr[i]) {
            largest = l;
        }
        if (r < this.heapSize && this.arr[r] > this.arr[largest]) {
            largest = r;
        }
        if (largest !== i) {
            const temp = this.arr[i];
            this.arr[i] = this.arr[largest];
            this.arr[largest] = temp;
            this.MaxHeapify(largest);
        }
    }

    // Returns the index of the parent
    // of the element at ith index.
    parent(i) {
        return Math.floor((i - 1) / 2);
    }

    // Returns the index of the left child.
    lChild(i) {
        return 2 * i + 1;
    }

    // Returns the index of the
    // right child.
    rChild(i) {
        return 2 * i + 2;
    }

    // Removes the root which in this
    // case contains the maximum element.
    removeMax() {
        // Checking whether the heap array
        // is empty or not.
        if (this.heapSize <= 0) {
            return null;
        }
        if (this.heapSize === 1) {
            this.heapSize -= 1;
            return this.arr[0];
        }

        // Storing the maximum element
        // to remove it.
        const root = this.arr[0];
        this.arr[0] = this.arr[this.heapSize - 1];
        this.heapSize -= 1;

        // To restore the property
        // of the Max heap.
        this.MaxHeapify(0);

        return root;
    }

    // Increases value of key at
    // index 'i' to new_val.
    increaseKey(i, newVal) {
        this.arr[i] = newVal;
        while (i !== 0 && this.arr[this.parent(i)] < this.arr[i]) {
            const temp = this.arr[i];
            this.arr[i] = this.arr[this.parent(i)];
            this.arr[this.parent(i)] = temp;
            i = this.parent(i);
        }
    }

    // Returns the maximum key
    // (key at root) from max heap.
    getMax() {
        return this.arr[0];
    }

    curSize() {
        return this.heapSize;
    }

    // Deletes a key at given index i.
    deleteKey(i) {
        // It increases the value of the key
        // to infinity and then removes
        // the maximum value.
        this.increaseKey(i, Infinity);
        this.removeMax();
    }

    // Inserts a new key 'x' in the Max Heap.
    insertKey(x) {
        // To check whether the key
        // can be inserted or not.
        if (this.heapSize === this.maxSize) {
            console.log("\nOverflow: Could not insertKey\n");
            return;
        }

        let i = this.heapSize;
        this.arr[i] = x;

        // The new key is initially
        // inserted at the end.
        this.heapSize += 1;



        // The max heap property is checked
        // and if violation occurs,
        // it is restored.
        while (i !== 0 && this.arr[this.parent(i)] < this.arr[i]) {
            const temp = this.arr[i];
            this.arr[i] = this.arr[this.parent(i)];
            this.arr[this.parent(i)] = temp;
            i = this.parent(i);
        }
    }
}


// Driver program to test above functions.

// Assuming the maximum size of the heap to be 15.
const h = new MaxHeap(15);

// Asking the user to input the keys:
console.log("Entered 6 keys:- 3, 10, 12, 8, 2, 14 \n");

h.insertKey(3);
h.insertKey(10);
h.insertKey(12);
h.insertKey(8);
h.insertKey(2);
h.insertKey(14);


// Printing the current size
// of the heap.
console.log(
    "The current size of the heap is " + h.curSize() + "\n"
);


// Printing the root element which is
// actually the maximum element.
console.log(
    "The current maximum element is " + h.getMax() + "\n"
);


// Deleting key at index 2.
h.deleteKey(2);


// Printing the size of the heap
// after deletion.
console.log(
    "The current size of the heap is " + h.curSize() + "\n"
);


// Inserting 2 new keys into the heap.
h.insertKey(15);
h.insertKey(5);

console.log(
    "The current size of the heap is " + h.curSize() + "\n"
);

console.log(
    "The current maximum element is " + h.getMax() + "\n"
);

Output
Entered 6 keys:- 3, 10, 12, 8, 2, 14 

The current size of the heap is 6

The current maximum element is 14

The current size of the heap is 5

The current size of the heap is 7

The current maximum e...

Related Posts:

Recommended DSA Problems:

Graphs

A graph is a collection of nodes (vertices) and edges connecting them.

  • Vertices (V): points/nodes
  • Edges (E): connections between nodes
  • Can be directed or undirected, weighted or unweighted.

JS does not have a built-in Graph class, but you can implement it using adjacency list:

JavaScript
const graph = new Map();

// Add vertices
graph.set(0, [1, 2]);
graph.set(1, [2]);
graph.set(2, [0]);

console.log(graph);

Output
Map(3) { 0 => [ 1, 2 ], 1 => [ 2 ], 2 => [ 0 ] }

Related Posts:

Recommended DSA Problems:

Dynamic Programming (DP)

Dynamic Programming is a commonly used algorithmic technique used to optimize recursive solutions when same subproblems are called again.

  • The core idea behind DP is to store solutions to subproblems so that each is solved only once.
  • To solve DP problems, we first write a recursive solution in a way that there are overlapping subproblems in the recursion tree (the recursive function is called with the same parameters multiple times)
  • To make sure that a recursive value is computed only once (to improve time taken by algorithm), we store results of the recursive calls.
  • There are two ways to store the results, one is top down (or memoization) and other is bottom up (or tabulation).

Related Posts:

Recommended DSA Problems:


Article Tags :

Explore