Variables and Assignment
Giving names to values, changing what a name refers to, and naming things well.
What is it?
A variable is a name that refers to a value so you can use it later. Instead of writing 19.99 everywhere, you write price, and the program looks up what price currently refers to.
Assignment is how you bind a name to a value. In most languages it's a single =:
- price = 19.99 means "make price refer to 19.99". It's an action, not a statement of fact. - Reassignment points the name at a new value: price = 24.99.
That's why = is not equality. Checking whether two values are equal uses == (Python, C) or === (JavaScript). So count = count + 1 is perfectly sensible: compute count + 1, then store the result back in count.
A constant is a name you don't intend to reassign. JavaScript enforces it with const. Python has no enforced constants; by convention, ALL_CAPS names like MAX_RETRIES mean "don't change this".
Naming conventions make code readable:
- Python:
snake_casefor variables and functions,UPPER_SNAKEfor constants. - JavaScript:
camelCasefor variables and functions,PascalCasefor classes. - Choose names that say what the value means:
total_price, nottporx.
Explain like I'm 10
A variable is a name tag, not a box. Assignment sticks the tag on a value. Reassignment peels the tag off and sticks it on a different value; the old value doesn't change, it just loses that tag.
Examples
Assign, read, reassign
score = 10 # bind the name "score" to 10
print(score) # 10
score = score + 5 # read score (10), add 5, bind score to 15
print(score) # 15
score += 1 # shorthand for score = score + 1
print(score) # 16
print(score == 16) # True (comparison, not assignment)The right-hand side is always evaluated first, then the result is bound to the name on the left.
let, const, and constants in JavaScript
const TAX_RATE = 0.2; // never reassigned
let subtotal = 50; // will change
subtotal = subtotal + 25;
const total = subtotal * (1 + TAX_RATE);
console.log(total); // 90
// TAX_RATE = 0.25; // TypeError: Assignment to constant variable.
const cart = ["apple"];
cart.push("pear"); // allowed! const stops reassignment, not mutation
console.log(cart); // ["apple", "pear"]Use const by default and let only when the name must be reassigned. Avoid var in modern code. const locks the binding, not the contents of an object or array.
Swapping and multiple assignment
a, b = 1, 2
a, b = b, a # swap without a temporary variable
print(a, b) # 2 1
x = y = 0 # both names refer to 0Python evaluates the whole right side before assigning, which makes swapping one line. JavaScript can do the same with [a, b] = [b, a];.
How it works
When the program runs price = 19.99:
1. The right side is evaluated, producing a value somewhere in memory. 2. The name price is recorded in the current scope (a table of names visible at this point in the code) as referring to that value.
Reading price later looks the name up and returns its current value. Reading a name that was never assigned raises an error: NameError in Python, ReferenceError in JavaScript.
In dynamically typed languages (Python, JavaScript) a name can refer to a value of any type, and reassignment can switch types. In statically typed languages (C, Java), a variable is declared with a type and is tied to a fixed-size memory slot of that type:
int count = 3; reserves space for an int named count.
score = 10 score = score + 5
score ──► 10 score ──┐ 10 (no name points here now)
└─► 15
"=" means "make the name on the left refer to the value on the right"
"==" asks "are these two values equal?"Why does it exist?
Programs need to remember things between steps: a running total, the current user, a setting. Names make code readable (tax_rate explains itself; 0.2 doesn't) and let you change a value in one place instead of everywhere it's used.
When to use it
- To store results you'll use again, instead of recomputing them.
- To give a meaningful name to a "magic number" (
SECONDS_PER_DAY = 86400). - To break a long expression into named steps that read like an explanation.
- To track state that changes, like a counter in a loop.
When not to use it
- Don't create a variable for a value used once when the expression is already clear. - Avoid reusing one name for unrelated things (data that's first a string, then a list, then a count); make new, well-named variables instead. - Avoid global variables shared across a whole program; pass values to functions instead.
Common mistakes
Writing
if x = 5when you meanif x == 5. Python rejects it as a syntax error; in C and JavaScript it assigns 5 and is always true.Using a variable before assigning it, or misspelling its name, which creates a
NameError/ReferenceError(or, in sloppy-mode JavaScript, silently creates a new global).Thinking
constmakes an object or array immutable in JavaScript. It only prevents reassignment of the name.Vague names like
data,temp,x2or single letters outside tiny loops.Expecting
b = ato copy a list. Both names now refer to the same list, so changing it through one name is visible through the other.
Practice exercises
- Easy:
Create variables for a product's name, price and quantity, compute the total cost into a new variable, and print a sentence that uses all of them.
- Medium:
Predict, then check, the final values:
a = 3; b = a; a = a * 2; b = b + a. Draw the names-to-values diagram after each line. - Hard:
Take a short program full of single-letter names and magic numbers (write one with at least five) and refactor it with descriptive names and named constants. Explain each choice.
Interview questions
What's the difference between `=` and `==`?
= is assignment: it binds a name to a value. == is a comparison that evaluates to true or false. JavaScript also has ===, which compares without type conversion and is preferred.
What's the difference between `let`, `const` and `var` in JavaScript?
const and let are block-scoped; const can't be reassigned, let can. var is function-scoped and hoisted with an initial value of undefined, which causes subtle bugs, so modern code avoids it.
Does Python have constants?
Not enforced ones. By convention, module-level UPPER_SNAKE_CASE names are treated as constants. Type checkers can enforce it with typing.Final.
What does `x = x + 1` mean, given that it's false as math?
It's an instruction, not an equation: evaluate x + 1 using the current value of x, then rebind x to the result.
Output-prediction (Python): `a = [1, 2]; b = a; b.append(3); print(a)`?
[1, 2, 3]. b = a makes both names refer to the same list; it doesn't copy it. Use a.copy() or list(a) for a copy.
Is a variable a box that holds a value?
In Python and JavaScript, it's closer to a label that refers to a value; several names can refer to the same object. In C, a variable really is a named, typed region of memory that holds the value directly.
What makes a good variable name?
It describes what the value means, not its type or how it's computed, is as short as clarity allows, follows the language's convention, and uses units or plurals when helpful (timeout_seconds, users).
What happens if you read a variable that was never assigned?
Python raises NameError; JavaScript raises ReferenceError (and reading a let/const before its declaration line also throws, due to the temporal dead zone). In C, a declared but uninitialized local holds an indeterminate value, and reading it is undefined behavior.
How do you swap two variables?
With a temporary variable in any language, or with tuple/destructuring assignment: a, b = b, a in Python, [a, b] = [b, a] in JavaScript.