Skip to content

Extract Variable

Take a piece of a larger expression, assign it to a well-named local variable, and use that name in place of the original sub-expression. Also known as Introduce Explaining Variable.

This cures the cryptic one-liner — an expression so dense you have to mentally parse it every time you read it. A boolean condition stitched together from three comparisons, or a price formula with magic arithmetic, hides its meaning inside punctuation. Naming each part turns the line into something you can read aloud.

A shipping check buries its meaning in one boolean expression. Naming the parts reveals the rules.

// Before
function isEligibleForFreeShipping(order: Order): boolean {
return order.total > 50 && order.country === 'TH' && !order.isGift;
}
// After
function isEligibleForFreeShipping(order: Order): boolean {
const overThreshold = order.total > 50;
const domestic = order.country === 'TH';
const giftExcluded = !order.isGift;
return overThreshold && domestic && giftExcluded;
}
  1. Check the sub-expression has no side effects — extracting one that mutates state can change behaviour.
  2. Declare an immutable local variable and assign the sub-expression to it.
  3. Give the variable a name that states what the value means, not how it is computed.
  4. Replace the original sub-expression with the new variable.
  5. Run your tests.
  6. If the same sub-expression appears more than once in scope, replace each occurrence and test again.

Use it for debugging (a named local is easy to inspect), for breaking a long formula into reviewable pieces, and to make a condition self-documenting. Within a single function a local is enough; when the same explanation is useful across the whole object, prefer Replace Temp with Query or extracting a method instead.

The inverse is Inline Variable: when a variable’s name adds nothing over the expression it holds, substitute the expression back and drop the variable.

What is the goal of Extract Variable?
What must you check before extracting a sub-expression into a variable?
What is the inverse of Extract Variable?