JavaScript
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Types
-
Section 3: Strings and Numbers in Depth
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Objects and Arrays
-
Section 7: Maps, Sets, and Symbols
-
Section 8: Asynchronous JavaScript
-
Section 9: Object-Oriented and Prototypes
-
Section 10: The DOM
-
Section 11: Browser APIs
-
Section 12: Modern JavaScript (ES2015-ES2025)
-
Section 13: Functional Programming Patterns
-
Section 14: Error Handling and Debugging
-
Section 15: Testing
-
Section 16: Accessibility for JavaScript Developers
-
Section 17: Internationalization and Localization
-
Section 18: Performance
-
Section 19: Node.js Fundamentals
-
Section 20: Regular Expressions
-
Section 21: Design Patterns in JavaScript
-
Section 22: Security Basics
-
Section 23: Data Structures and Algorithms in JavaScript
-
Section 24: Practical Projects
-
Section 25: More Advanced Async Patterns
-
Section 26: More Object and Class Practice
-
Section 27: Working with Dates and Internationalization
-
Section 28: Web Components
-
Section 29: More DOM and Browser Practice
-
Section 30: Build Tooling for Vanilla JavaScript
-
Section 31: More Practice Projects
-
Section 32: Interview and Algorithm Practice
-
Section 33: Error Objects (MDN Reference)
-
Section 34: TypedArrays and Binary Data
-
Section 35: Reflection and Metaprogramming (MDN Reference)
-
Section 36: More Global Functions (MDN Reference)
177: Implementing Binary Search
How do I actually translate the "divide and conquer" logic into JavaScript?
When you're implementing binary search, you aren't just looping through a list; you're shrinking the search area. I find it easiest to think of it as two pointers—low and high—that act like walls closing in on your target. You keep checking the middle element, and depending on whether your target is higher or lower, you move one of those walls.
Let's say we have a sorted list of employee IDs and we're looking for ID 1042. Here is how I'd write that:
function binarySearch(sortedArray, target) {
let low = 0;
let high = sortedArray.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const guess = sortedArray[mid];
if (guess === target) {
return mid; // Found it!
}
if (guess > target) {
high = mid - 1; // Target is in the left half
} else {
low = mid + 1; // Target is in the right half
}
}
return -1; // Target isn't in the array
}
const employeeIds = [101, 205, 310, 450, 1042, 1100, 1250];
console.log(binarySearch(employeeIds, 1042)); // 4
Why is the sorted array a hard requirement?
This is the most common point of confusion. Binary search relies on a fundamental assumption: if the middle element is larger than your target, every single element to the right of that middle point must also be larger than your target. That's the only reason we can safely throw away half the array in one go.
If the array is unsorted, that logic collapses. Imagine looking for the number 10 in [20, 5, 10, 2, 15]. If your midpoint is 10, you're lucky. But if your midpoint is 5, and you assume that because 5 is less than 10, the target must be to the right, you might be right this time—but you've lost the ability to prove it. In an unsorted list, the target could be anywhere, so you're forced back into a linear search (checking every single item), which defeats the whole purpose of using this algorithm.
Why do I need Math.floor() when calculating the midpoint?
Coming from languages like Java or C++, you might be used to integer division where 5 / 2 just equals 2. JavaScript doesn't work like that. In JS, (0 + 5) / 2 gives you 2.5.
Since array indices must be integers, trying to access sortedArray[2.5] will just return undefined, and your logic will break immediately. I always use Math.floor() to round down to the nearest whole number. It doesn't matter if you round up or down, as long as you are consistent and end up with a valid index.
Is binary search always the "better" choice?
Not necessarily. It's incredibly fast—O(log n) time complexity, for the math nerds—but it comes with a "cost of entry." That cost is the sorting.
If you have a list that is already sorted, binary search is a no-brainer. But if you have an unsorted list and you only need to search it once, it's actually faster to just do a linear search. Why? Because sorting an array usually takes O(n log n) time, which is more expensive than a simple O(n) linear scan. I only reach for binary search when the data is already sorted, or when I'm sorting the data once and then performing hundreds of searches over time.
📋 Practical Task
Implement a Sorted Transaction Finder
You are building a financial ledger tool. You have an array of transaction IDs that are already sorted in ascending order. Your task is to implement the findTransactionIndex function using the binary search algorithm.
Requirements:
- The function should take two arguments: the
transactionsarray and thetargetId. - If the
targetIdexists in the array, return its index. - If the
targetIddoes not exist, return-1. - Do not use built-in JavaScript methods like
indexOf()orfindIndex(), as the goal is to implement the binary search logic manually.
const transactions = [10023, 10045, 10089, 10112, 10150, 10201, 10255];
function findTransactionIndex(transactions, targetId) {
// Your code here
}
// Test cases:
console.log(findTransactionIndex(transactions, 10150)); // Should return 4
console.log(findTransactionIndex(transactions, 10023)); // Should return 0
console.log(findTransactionIndex(transactions, 99999)); // Should return -1
There are no comments for now.