01 / 21

JavaScript
Refactoring

Learn to transform messy, duplicated code into clean, maintainable functions by extracting patterns, eliminating repetition, and improving clarity.

JavaScript

What Is Refactoring?

Refactoring is the process of restructuring existing code without changing what it does. The program's inputs and outputs stay exactly the same: only the internal structure improves.

Refactoring targets three things: duplication (repeated code), complexity (hard-to-follow logic), and poor naming (unclear variable and function names).

Why Does Refactoring Matter?

✓ Readability
Other developers (and your future self) can understand the code quickly.
✓ Maintainability
Fixing bugs and adding features becomes safer: change one place, not ten.
✓ Fewer Bugs
Duplicated logic is a breeding ground for inconsistencies and errors.

Recognizing Code Smells

A code smell is a surface-level indicator that something deeper may be wrong. Smells do not mean the code is broken: they signal it could be better structured.

Code Smells Duplication Long Functions Magic Numbers Poor Names

The DRY Principle

DRY stands for Don't Repeat Yourself. Every piece of knowledge in your code should have a single, authoritative source. If you copy-paste logic, you create multiple places that must stay in sync.

✕ WET
Same validation logic appears in 3 event handlers. A bug fix must be applied 3 times.
✓ DRY
Validation lives in one function. All 3 handlers call it. Fix once, fixed everywhere.

Refactoring vs Rewriting

Refactoring Rewriting
Behavior changes? No Yes
Step size Small, incremental Large, all-at-once
Risk level Low High
Tests still pass? Always Often need new tests
Goal Improve structure Replace functionality

How to Refactor Step by Step

1
Identify the smell. Look for repeated blocks, long functions, or unclear names.
2
Ensure tests exist. You need a safety net: write tests if none exist.
3
Make one small change. Extract a function, rename a variable, or remove a duplicate.
4
Run tests. Verify behavior is unchanged.
5
Repeat. Continue until the code is clean and readable.

Example 1: Extract Function

✕ Before: Duplicated logic
// Calculate area of rectangle 1 let area1 = 10 * 5; console.log("Area:", area1); // Calculate area of rectangle 2 let area2 = 8 * 3; console.log("Area:", area2); // Calculate area of rectangle 3 let area3 = 12 * 7; console.log("Area:", area3);
↓ Extract a function
✓ After: Single reusable function
function printArea(width, height) { const area = width * height; console.log("Area:", area); } printArea(10, 5); printArea(8, 3); printArea(12, 7);

Example 2: Rename for Clarity

✕ Before: Cryptic names
function calc(a, b, c) { return a * b * (1 + c); }
↓ Rename everything
✓ After: Self-documenting names
function calculateTotalPrice(quantity, unitPrice, taxRate) { return quantity * unitPrice * (1 + taxRate); }

Example 3: Replace Magic Numbers

✕ Before: Magic number 0.08
function getTotal(price) { return price + price * 0.08; }
↓ Extract to a named constant
✓ After: Named constant
const TAX_RATE = 0.08; function getTotal(price) { return price + price * TAX_RATE; }

Example 4: Simplify Conditionals

✕ Before: Nested, repetitive if-else
function getDiscount(type) { if (type === "student") { return 0.2; } else if (type === "senior") { return 0.15; } else if (type === "member") { return 0.1; } else { return 0; } }
↓ Use a lookup object
✓ After: Data-driven approach
const DISCOUNTS = { student: 0.2, senior: 0.15, member: 0.1, }; function getDiscount(type) { return DISCOUNTS[type] || 0; }

The Refactoring Cycle

Identify Smell Write / Check Tests Make Small Change Run Tests Clean? Done. Else: Repeat Pass ✓ Fail? Undo and retry

Technique: Extract Function

Extract Function is the most common refactoring move. When you see a block of code that does one specific thing, pull it into its own named function.

1
Spot the block. Find lines that work together toward a single purpose.
2
Name the purpose. Choose a verb-noun name: calculateTotal, formatDate, validateEmail.
3
Identify inputs. What variables does the block read? These become parameters.
4
Move and call. Cut the block into the new function, then replace the original with a function call.

Example 5: Loop to Higher-Order Function

✕ Before: Manual loop with accumulator
let total = 0; for (let i = 0; i < prices.length; i++) { if (prices[i] > 10) { total += prices[i]; } }
↓ filter + reduce
✓ After: Declarative chain
const total = prices .filter(price => price > 10) .reduce((sum, price) => sum + price, 0);

Common Mistakes

✕ Refactoring Without Tests
Changing code without a safety net means you won't know if you broke something until much later.
✕ Too Many Changes at Once
Making five refactoring moves before testing makes it impossible to find which change introduced a bug.
✕ Over-Abstracting
Creating a generic function used only once adds complexity without reducing duplication. Abstract when you see a third repetition.

Refactoring Techniques Summary

Technique When to Use Result
Extract Function Repeated code blocks One reusable function
Rename Variable Unclear names (a, x, tmp) Self-documenting code
Replace Magic Number Hard-coded literals Named constant
Simplify Conditional Long if-else chains Lookup object or map
Replace Loop Manual for-loop patterns filter / map / reduce

Question 1 of 5

What is the primary goal of refactoring?

Question 2 of 5

Which refactoring technique was applied to transform Code A into Code B?

Question 3 of 5

What does the acronym DRY stand for in software development?

Question 4 of 5

The numbers 0.15 and 0.08 in this code are examples of which code smell?

Question 5 of 5

When is the safest time to refactor code?