Refactoring is the systematic restructuring of existing code while keeping its externally observable behavior unchanged. It makes code easier to test, reuse, maintain, and change safely. section 4.0 section 4.9
A practical refactoring starts with a working function and separates its responsibilities. Extract a calculation, identify its inputs and outputs, make implicit data explicit, and leave actions such as global updates or DOM changes at the boundary. section 4.0 section 4.9
Useful refactoring moves include:
- Extract a subroutine, then convert global reads into arguments and global writes into return values. section 4.9
- Spot a code smell when a changing value appears in a function name; add that value as an explicit argument and update callers. section 10.1 section 10.3
- Replace changing code bodies with callbacks when the surrounding before-and-after structure is shared. section 10.1
- Rewrite loops from their behavior or from structural clues: map commonly produces one result per element, while reduce combines elements. section 13.6
- Prefer small steps: make data, operate on whole arrays, and split callbacks when they perform more than one job. section 13.10 section 13.8
Extracting a shopping-cart calculation
A function that calculates a total, writes a global shopping_cart_total, and updates the DOM can first extract calc_total(). Then calc_total() can accumulate in a local variable, return the total, and accept shopping_cart as cart. The outer function assigns the result and continues its action work. The calculation is now easier to reuse and test without the global cart. section 4.9





















