01 / 21

Solution
Tradeoffs

Every line of code is a choice. Learn to evaluate tradeoffs between readability, performance, and maintainability to write better JavaScript.

JavaScript

What Is a Tradeoff?

A tradeoff occurs whenever choosing one approach means giving up some benefit of another. In software, no solution is perfect on every dimension: gaining speed might cost clarity, and vice versa.

Readability
How easily a human can understand your code at a glance.
Performance
How fast your code runs and how much memory it uses.
Maintainability
How easily your code can be changed or extended later.

Why Tradeoffs Matter

Professional developers spend far more time reading code than writing it. A clever one-liner might run faster, but if teammates can't understand it, bugs multiply and progress slows.

That said, performance matters when your code runs in tight loops, handles large datasets, or powers real-time interfaces. The skill is knowing when each dimension matters most.

The Tradeoff Spectrum

Readable Performant Clear names Small functions Balanced Sweet spot Bit tricks Micro-optimise Aim here most of the time

The Core Principle

1
Make it work: Write code that produces the correct output.
2
Make it clear: Refactor for readability: names, structure, comments.
3
Make it fast: Profile, identify bottlenecks, then optimise only those.

Measuring with Big-O

Big-O notation describes how execution time grows as input size \( n \) increases. Understanding it helps you compare approaches before writing a single benchmark.

Input size (n) Time \( O(1) \) \( O(n) \) \( O(n^2) \) \( O(n \log n) \)

Readability vs Performance

Readable Approach Performant Approach
Goal Clarity for humans Speed for machines
Naming Descriptive, verbose Short, terse
Abstractions Many small functions Inlined logic
Data structures Arrays, plain objects Typed arrays, Maps, Sets
When to choose Most application code Hot paths, large data

Decision Checklist

1
Does it work correctly? Correctness always comes first.
2
Can a teammate read it in 30 seconds? If not, add names, comments, or split functions.
3
Is it on a hot path? If this code runs thousands of times per second, performance matters.
4
Have you measured? Use console.time() or browser DevTools before optimising.
5
Document the tradeoff: If you choose speed over clarity, leave a comment explaining why.

Example 1: Summing an Array

Approach A: Readable
function sumArray(numbers) { let total = 0; for (const num of numbers) { total += num; } return total; }
Approach B: Concise
const sumArray = nums => nums.reduce((a, b) => a + b, 0);

Example 2: Finding Duplicates

Approach A: Nested Loop – \( O(n^2) \)
function hasDuplicates(arr) { for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[i] === arr[j]) return true; } } return false; }
Approach B: Set – \( O(n) \)
function hasDuplicates(arr) { return new Set(arr).size !== arr.length; }

Example 3: A Real Tradeoff

Readable: filter + map
const result = users .filter(u => u.age >= 18) .map(u => u.name);
Performant: single loop
const result = []; for (let i = 0; i < users.length; i++) { if (users[i].age >= 18) { result.push(users[i].name); } }

Context Changes the Answer

Which approach? Choose Readable Team project Small dataset Choose Performant Hot loop / animation Large dataset (>10K) Always document why

The "right" answer depends on who reads the code, how much data flows through it, and how often it runs. There is no universal winner.

Maintainability: The Third Dimension

Maintainability is how easily your future self (or a colleague) can modify the code when requirements change. It overlaps with readability but also includes structure.

Single Responsibility
Each function does one thing. Easy to update without side effects.
DRY Principle
Don't Repeat Yourself. Shared logic lives in one place.
Modularity
Self-contained modules with clear interfaces. Swap parts easily.

Refactoring for Clarity

Before: Cryptic
const r = d.filter(x => x.s > 90 && x.a).map(x => x.n);
After: Clear
const MIN_SCORE = 90; const topActiveStudents = students .filter(student => student.score > MIN_SCORE) .filter(student => student.isActive) .map(student => student.name);

Common Mistakes

Premature Optimisation
Spending hours shaving microseconds off code that runs once. Measure first, optimise second.
Clever One-Liners
Writing regex or bitwise tricks that save lines but confuse every reviewer. Clarity beats brevity.
Ignoring Big-O
Using nested loops on large datasets when a Set or Map would give \( O(n) \) time. Know your data structures.
No Documentation
Choosing a non-obvious approach without explaining the tradeoff in a comment. Future readers will be confused.

Summary Table

Factor Readability Performance Maintainability
Priority Default first When measured Always
Naming Descriptive Short OK Consistent
Functions Small, named Inline if hot Single purpose
Data structures Simple Specialised Well-abstracted
Risk Verbose code Hard to debug Over-engineering

Question 1 of 5

Your team is building a to-do app with at most 100 items. A colleague writes a for-loop and you suggest .filter().map() instead. What is the best justification?

Question 2 of 5

Which approach has the worst Big-O complexity for checking if an array contains duplicates?

Question 3 of 5

A developer uses single-letter variable names and bitwise operators to make an animation loop run 5% faster. What should you tell them?

Question 4 of 5

Which of the following is NOT an example of improving readability?

Question 5 of 5

You discover a function runs 500,000 times per page load and uses .filter().map() on a 10,000-element array. What is the best first step?