A global variable is accessible across broad program scope instead of being confined to one function or block. That convenience also hides data flow: reading a global is an implicit input, while modifying one is an implicit output. section 4.10
Global variables make reuse and testing harder when functions depend on shared application state. A calculation becomes easier to reuse when its inputs arrive as arguments and its results leave through return values. section 4.5 section 4.8
Refactor global state incrementally:
- Identify each global read or write and classify it as an implicit input or output. section 4.10
- Replace a global read with an argument, as with passing shopping_cart into add_item() or calc_cart_total(). section 4.10 section 15.28
- Replace shared mutable data with a local variable or a returned copy when practical; copy-on-write supports the shopping-cart example. section 15.27 section 4.10
- Inventory global mutable variables, remove one dependency, and repeat rather than attempting a single large rewrite. section 19.8
From shared cart state to explicit data flow
Instead of letting add_item() read shopping_cart directly, call add_item(shopping_cart, name, price). A stronger refactoring copies the cart, adds the item, returns the new cart, and assigns it back. The same principle changes calc_tax() from reading shopping_cart_total to accepting amount. In asynchronous code, making total local reduces interference between interleaved timelines, although shared cart and DOM resources may still need further isolation. section 4.10 section 15.26 section 15.28
function add_item_to_cart(name, price) { #1
shopping_cart =
add_item(shopping_cart, name, price);
calc_cart_total();
}
function add_item(cart, name, price) {
var new_cart = cart.slice(); #2
new_cart.push({ #3
name: name,
price: price
});
return new_cart; #4
}
Compare the global-cart version with the copy-on-write refactoring: the cart becomes an explicit input and the updated value becomes an explicit output. section 4.10











