Skip to content

Inline Variable

Sometimes a local variable is just a second name for an expression you already understand. It does not clarify anything and it does not get reused — it only stands between you and the code that matters. Inline Variable removes that middleman: substitute the expression for the variable and delete the declaration. The result is one fewer name to track.

You meet a variable whose name says no more than the expression it holds. let basePrice = order.basePrice; followed by a single use of basePrice is noise — the reader has to scroll up to confirm that basePrice really is order.basePrice and nothing more. The variable promised an explanation and delivered a synonym.

This is the exact inverse of Extract Variable. There you add a name because a sub-expression is cryptic; here you remove a name because it never earned its keep. The judgement is the same in both directions: does the name make the code clearer than the raw expression? If not, inline it.

A shipping check that binds two variables which simply mirror fields, then uses each once.

// Before
function canShipFree(order: Order): boolean {
const basePrice = order.basePrice;
const overThreshold = basePrice > 100;
return overThreshold;
}
// After
function canShipFree(order: Order): boolean {
return order.basePrice > 100;
}
  1. Check that the expression assigned to the variable has no side effects — inlining must not change when or how often that expression runs.
  2. If the variable is not already read-only, make it so (a const, final, or single-assignment binding). If the compiler complains, the variable is reassigned and you should stop: it is doing more than mirroring.
  3. Find the first place the variable is read and replace that read with the expression.
  4. Run your tests.
  5. Repeat for each remaining read, one at a time, testing as you go.
  6. When no reads remain, delete the declaration.
  7. Run your tests once more.

Inline a variable when its name carries no information the expression does not already carry, and when it is used in only one or two nearby places. Stripping it out shortens the function and removes a hop for the reader.

Do not inline when the variable’s name documents a non-obvious meaning, when the expression is repeated many times (a name then avoids both duplication and recomputation), or when the expression is expensive and the variable caches its result. In those cases the inverse — Extract Variable — is the move you want instead.

When is a variable a good candidate to inline?
Inline Variable is the inverse of which refactoring?
What must you confirm about the expression before inlining it?
When should you NOT inline a variable?