Programming Fundamentals › Programming Basics
Constant
A name bound to a value that cannot be reassigned.
Also known as: constants, const, immutable binding, named constant
A constant is a name bound to a value that doesn’t change while the program runs.
MAX_RETRIES = 3 # Python has no enforcement; ALL_CAPS is a convention
TAX_RATE = 0.2
const MAX_RETRIES = 3; // JavaScript: cannot be reassigned
static final int MAX_RETRIES = 3;
Why use them
Replace magic numbers and repeated strings with a named value:
if attempts > 3: # why 3?
if attempts > MAX_RETRIES: # clear, and changeable in one place
- Meaning: the name explains the number.
- One place to change: update
TAX_RATEonce, not in forty places. - Safety: where the language enforces it, accidental reassignment is an error.
Caution: constant doesn’t always mean immutable
In JavaScript, const stops reassigning the variable, but an object or array can still change inside:
const config = { debug: false };
config.debug = true; // allowed
See var, let and const and mutable vs immutable.
Habits
- Name them in
UPPER_SNAKE_CASEwhere that’s the convention. - Group related constants, or use an
enumfor fixed sets of options. - Put configuration that changes per environment in configuration, not constants.
- Don’t over-extract:
ONE = 1adds nothing. Name values that carry meaning.