Programming fundamentals
Big O Notation Explained Simply, With JavaScript Examples
Big O notation describes how the work a piece of code does grows as its input grows, not how many seconds it takes on one machine. Once you can count how many times a loop touches the data, you can tell at a glance whether code will stay fast when the input gets a hundred times bigger.
By CodingMarble · Published · 5 min read

What Big O actually describes
Suppose a function takes 5 milliseconds on your laptop. That number tells you very little. A different laptop, a busy server or a cold cache will change it. What does not change from machine to machine is the shape of the relationship between input size and work. If you double the input and the work doubles, that is linear growth. If you double the input and the work quadruples, that is quadratic growth. Big O is the vocabulary for naming those shapes.
The letter n stands for the size of the input, for example the number of items in an array. O(n) is read as order n and means the work grows in proportion to n. Big O deliberately drops two things. It drops constant factors, so a loop that does three steps per item and a loop that does one step per item are both O(n). It also drops lower-order terms, so n squared plus n is simply O(n squared), because for large n the squared part dominates. By convention Big O describes the worst case unless someone says otherwise.
The practical question it answers is: will this still be acceptable when the data grows? A report that handles 200 rows in a demo may need to handle 200,000 rows a year later, and the growth shape decides whether that is a non-event or an outage.
The five shapes you will meet most
Most everyday code falls into a handful of categories. The snippet below shows one small function for each, so you can compare how each one touches the input.
// O(1): constant. One step, however long the array is.
const first = (items) => items[0];
// O(log n): halve the search range each step (array must be sorted).
function binarySearch(sorted, target) {
let lo = 0, hi = sorted.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (sorted[mid] === target) return mid;
if (sorted[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
// O(n): touch each item once.
const total = (items) => items.reduce((sum, x) => sum + x, 0);
// O(n log n): sorting with a comparison sort.
const sortedCopy = (items) => [...items].sort((a, b) => a - b);
// O(n^2): compare every item with every other item.
function hasDuplicate(items) {
for (let i = 0; i < items.length; i++) {
for (let j = i + 1; j < items.length; j++) {
if (items[i] === items[j]) return true;
}
}
return false;
}Reading the shapes in order: O(1) does not care about size at all. O(log n) grows so slowly that searching a sorted list of a million items needs only about twenty comparisons, because each step throws away half of what is left. O(n) is the honest baseline for anything that has to look at every item. O(n log n) is what good general-purpose sorting costs, which is why sorting inside a loop deserves suspicion. O(n^2) is the one to watch: ten times more data means roughly a hundred times more work, and that is where code that felt instant starts to hang.
How to count operations without a formula
You rarely need mathematics. Read the code and ask how many times each line runs as a function of n. A single loop over the input is n. A loop inside a loop, where both walk the input, is n times n. Two loops one after the other, not nested, are n plus n, which is still O(n). A loop that halves its remaining range each pass is log n. Something that calls a method on the inside needs that method's cost multiplied in: a loop over n items that calls array.includes on another array of n items is n times n, even though no second for keyword is visible.
That hidden-loop case is the most common way people write quadratic code by accident. Methods such as indexOf, includes, find, filter and splice all scan the array internally. Inside a loop they multiply the cost. The next section turns this into a concrete before and after.
A practical example: array search versus Set lookup
Imagine you have a list of users and a list of blocked ids, and you want the users who are not blocked. The first version looks harmless and is quadratic. The second builds a Set once, then checks membership in roughly constant time per lookup.
// Slow shape: includes() scans the whole blocked array for every user.
function allowedSlow(users, blockedIds) {
return users.filter((u) => !blockedIds.includes(u.id));
}
// Better shape: build a Set once, then each has() is about O(1).
function allowedFast(users, blockedIds) {
const blocked = new Set(blockedIds);
return users.filter((u) => !blocked.has(u.id));
}
const users = [{ id: 1 }, { id: 2 }, { id: 3 }];
console.log(allowedFast(users, [2])); // [{ id: 1 }, { id: 3 }]With n users and m blocked ids, the first version does up to n times m comparisons, and the second does about n plus m steps. Building the Set costs O(m) once, and each membership check afterwards is cheap on average. You trade a little extra memory for a large drop in work, which is the most common trade in this whole topic. To verify the claim in your own project, time both functions with arrays of 1,000, 10,000 and 100,000 items using console.time, and watch how each timing grows when you multiply the size by ten.
Space complexity: memory counts too
Big O also describes memory. A function that builds a new array the same length as its input uses O(n) extra space. A function that only keeps a running total uses O(1) extra space. The Set in the previous example is a space cost: O(m) extra memory bought the time saving. Neither side is automatically right. On a server handling a few thousand items, memory is cheap and the faster version wins. In a mobile app or a process that handles a stream of millions of records, holding everything in memory may be the actual problem, and a slower streaming approach that uses constant space is the better design.
Recursion hides space cost as well. Each recursive call sits on the call stack until it returns, so a recursive function that goes n levels deep uses O(n) stack space, and a very deep one can overflow the stack even when its time cost looks fine.
Why constants and small inputs still matter
Big O ignores constants, but your users do not. An O(n) algorithm that does a network call per item is far slower in practice than an O(n^2) algorithm that compares numbers in memory, as long as n stays small. For an array of ten items, almost any approach is fine, and the simplest code is usually the best code. A linear scan of a short array can even beat a hash lookup, because building and hashing carry their own fixed costs.
So Big O is a tool for predicting what happens as data grows, not a reason to rewrite every loop. The sensible order is to write the clear version first, know roughly how big the input can get, and optimise when the growth shape and the real input size say there will be a problem. Measure before and after, because intuition about performance is often wrong.
Practical tip: when you review code, look for a loop whose body calls includes, indexOf, find or filter on another collection. That pattern is quadratic in disguise. Ask what the largest realistic input is, and if the answer is more than a few thousand items, consider a Set or a Map built before the loop.
Reasoning about complexity when reviewing code
A short checklist is enough for most reviews. First, find what n is: users, rows, characters, requests. Second, find the loops and the hidden loops inside library calls. Third, ask whether the input can realistically grow, and by how much. Fourth, check the database as well: a query run inside a loop is a loop over the network, so fetching one row per item is O(n) round trips where one query with a list of ids might do the job. Sorting inside a loop, or repeatedly searching an unsorted array that could be indexed once, are the other recurring offenders.
Finally, state the cost in the pull request comment in plain words, such as this is linear in the number of orders, or this is quadratic but the list never exceeds fifty items. Writing it down forces the assumption into the open, and that assumption is exactly what future maintainers need when the list suddenly does exceed fifty.
Keep reading
- Programming fundamentalsData Structures Every Developer Should Know, in PracticeA data structure is a way of arranging data so that the operations you need most, such as lookup, insert or ordering, are cheap. Learning the seven or eight common ones, and what each does well, lets you choose the right container before you write the code instead of fixing a slow one afterwards.
- Programming fundamentalsDatabase Indexing Explained: When It Helps and When It HurtsA database index is a separate, sorted structure that lets the engine jump to matching rows instead of reading the whole table, at the cost of extra storage and slower writes. It only helps when your queries can actually use it, so the habit to build is checking the query plan with EXPLAIN rather than adding indexes on a hunch.
- Interview questions and cheat sheetsJavaScript Interview Questions and AnswersThis page gives you eighteen JavaScript interview questions, grouped from fundamentals to trick questions, each with a precise answer you can say aloud in under a minute. Code examples are short enough to rewrite on a whiteboard.
- Programming fundamentalsHow to Debug Code Systematically: A Repeatable MethodSystematic debugging means turning a vague failure into a small, repeatable one, forming a specific guess about the cause, and testing that guess instead of changing code at random. Follow the loop of reproduce, narrow, hypothesise, test, fix and protect, and most bugs become a matter of steady elimination.
Need this built properly for your business?
CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.