Day 7 — Binary Search in JavaScript

Welcome back to Day 7 of the DSA Master Course 2025!
Today, we’re diving into Binary Search, one of the most efficient and elegant search algorithms you’ll ever meet.


Binary Search is an algorithm used to find the position of a target value within a sorted array.
Instead of checking each element one by one like Linear Search, Binary Search divides the search space in half each time until it finds the target (or confirms it’s not there).

Think of it like looking for a word in a dictionary — you don’t start from the first page; you open in the middle, check if you need to go forward or backward, and repeat.


How Binary Search Works — Step-by-Step

  1. Start with two pointers — one at the start and one at the end of the array.

  2. Find the middle element.

  3. If the middle element is the target → return its index.

  4. If the target is less than the middle element → search the left half.

  5. If the target is greater than the middle element → search the right half.

  6. Repeat until the start pointer is greater than the end pointer (target not found).


Binary Search Visual


sqlCopyEditfunction binarySearch(array, target):
    left ← 0
    right ← length(array) - 1

    while left ≤ right:
        mid ← (left + right) / 2

        if array[mid] == target:
            return mid

        else if target < array[mid]:
            right ← mid - 1

        else:
            left ← mid + 1

    return -1

Binary Search in JavaScript — Iterative Approach

javascriptCopyEditfunction binarySearch(arr, target) {
    let left = 0;
    let right = arr.length - 1;

    while (left <= right) {
        let mid = Math.floor((left + right) / 2);

        if (arr[mid] === target) {
            return mid; // Found
        } else if (arr[mid] < target) {
            left = mid + 1; // Search right half
        } else {
            right = mid - 1; // Search left half
        }
    }
    return -1; // Not found
}

// Example usage
let numbers = [2, 5, 8, 12, 16, 23, 38, 45, 56, 72];
console.log(binarySearch(numbers, 23)); // Output: 5

Binary Search in JavaScript — Recursive Approach

javascriptCopyEditfunction binarySearchRecursive(arr, target, left = 0, right = arr.length - 1) {
    if (left > right) return -1; // Not found

    let mid = Math.floor((left + right) / 2);

    if (arr[mid] === target) return mid;
    else if (arr[mid] > target) {
        return binarySearchRecursive(arr, target, left, mid - 1);
    } else {
        return binarySearchRecursive(arr, target, mid + 1, right);
    }
}

// Example usage
let numbers = [2, 5, 8, 12, 16, 23, 38, 45, 56, 72];
console.log(binarySearchRecursive(numbers, 72)); // Output: 9

Time & Space Complexity

CaseTime Complexity
Best CaseO(1)
AverageO(log n)
WorstO(log n)
  • Space Complexity:

    • Iterative → O(1)

    • Recursive → O(log n) (due to call stack)


✅ The array/list is sorted.
✅ You need fast lookups in large datasets.
✅ Memory is not a major constraint.


❌ Forgetting that the array must be sorted before searching.
❌ Infinite loops caused by incorrect pointer updates.
❌ Integer overflow when calculating mid (use left + Math.floor((right - left) / 2)).


Practice Problems

  1. Search for a number in a sorted array.

  2. Find the first and last occurrence of a number in a sorted array.

  3. Guess the number game (Leetcode 374).


💡 Up Next — Day 8: We’ll explore Real-World Applications of Binary Search, including variations like lower bound, upper bound, and more.

#CodeWithGift #DSA2025 #JavaScript #DaySeven

1
Subscribe to my newsletter

Read articles from God'sgift Samuel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

God'sgift Samuel
God'sgift Samuel

About Me Tech enthusiast and developing web developer with a growing passion for blockchain technology. My journey spans 3 years of HTML/CSS crafting, 2 years of JavaScript exploration, and recent ventures into React, Node.js, and the blockchain space. Currently at the beginning of my blockchain journey while building a solid foundation in web development technologies. Fascinated by the potential of decentralized systems and eager to contribute to this evolving ecosystem. Technical Background I bring a diverse technical toolkit that includes: Strong foundation in web fundamentals (HTML/CSS: 3 years) Dynamic front-end development with JavaScript (2 years) and React (1 year) Modern UI implementation using Tailwind CSS and Bootstrap (7 months) Server-side programming with Node.js (1 year) and Python (2-3 years) Early-stage blockchain development knowledge Beginning exploration of Rust programming (4 months) Blockchain Journey While still at the beginner level in blockchain technology, I'm actively learning about distributed ledger concepts, smart contract fundamentals, and the broader implications of Web3. My interest in this space stems from a belief in the transformative potential of decentralized technologies and their ability to reshape digital interactions. Vision & Goals My development path is guided by a clear progression: mastering web development fundamentals, expanding into blockchain applications, and ultimately exploring the intersection of these technologies with artificial intelligence. I see tremendous potential in combining these domains to create innovative solutions for tomorrow's challenges. Collaboration Interests Open to connecting with fellow developers, blockchain enthusiasts, and mentors who share an interest in the convergence of web development and emerging technologies. Particularly interested in learning opportunities, knowledge exchange, and potential collaboration on projects that push the boundaries of what's possible in the decentralized space. Current Focus Deepening my understanding of React and Node.js ecosystems while simultaneously building knowledge in blockchain fundamentals and smart contract development. Committed to continuous learning and practical application of new skills.