Variables in Programming

πŸ“Œ Concept 3 of 13✍️ Written by Mark SullivanπŸ“… Reviewed 2026-04-21⏱ ~8 min read

A variable is a named container for a value. It's the simplest idea in programming and also the most important β€” almost every other concept manipulates variables in some way.

Bee, our debugging mascot

From Bee: When two variable names point to the same object, changing one changes both. This trips up beginners more than any other concept.

What Is a Variable?

A variable is a name your program uses to refer to a value. You assign a value to that name, then later you can read it back, change it, or pass it to other parts of the program. The name is for you (the programmer); the underlying memory location is for the computer.

The mental model: think of a variable as a labeled box. The label is the name, the contents of the box is the value. price = 9.99 creates a box labeled price that contains the number 9.99. Later, price = 19.99 swaps the contents of the box β€” same label, new value.

Declaring Variables in Three Languages

let score = 100;          // mutable β€” can be reassigned
const name = "Aisha";     // immutable β€” locked once set

score = 110;              // OK
// name = "Ben";          // ERROR

// var exists too but is older and rarely used in new code.
score = 100               # No keyword needed
name = "Aisha"

score = 110               # OK β€” Python lets you reassign anything

# Convention: ALL_CAPS for constants
PI = 3.14159
int score = 100;          // Type must be declared
String name = "Aisha";

score = 110;              // OK

final int MAX = 1000;     // final = constant, cannot reassign

Naming Rules and Conventions

Variable names have a few hard rules across most languages:

  • Must start with a letter or underscore (not a digit).
  • Can contain letters, digits, and underscores.
  • Cannot be a reserved keyword (if, for, class, etc.).
  • Are case-sensitive: Score and score are different variables.

Beyond the rules, conventions:

  • JavaScript and Java: camelCase β€” userScore, totalPrice.
  • Python: snake_case β€” user_score, total_price.
  • Constants in any language: UPPER_SNAKE_CASE β€” MAX_RETRIES, PI.
  • Names should describe what's stored: userAge beats x.

Real-World Use Cases

  • Tracking state in a game: let lives = 3; β€” decrement when the player dies.
  • Storing user input: const email = form.email.value;
  • Caching expensive results: const total = computeTotal(items); β€” compute once, reuse.
  • Loop counters: for (let i = 0; i < 10; i++) ... β€” i is a variable that updates each iteration.
  • Configuration values: const API_URL = "https://api.example.com";

Visualizing Assignment

price name (label) 9.99 value (contents) price = 9.99;

Assignment connects a name to a value. Reassignment changes the value the name points to.

Mutable vs. Immutable

Some variables can be reassigned (mutable); others are locked once set (immutable). The distinction:

  • JavaScript: let is mutable, const is immutable.
  • Python: there's no built-in const. Convention is to write the name in ALL_CAPS to signal "don't reassign me."
  • Java: any variable can be made immutable by adding the final keyword.

As a rule of thumb: prefer immutable when you can. It prevents bugs where a value changes unexpectedly.

Scope (Preview)

Scope is where a variable is visible. A variable declared inside a function isn't accessible outside it. A variable declared in a loop's body might not survive past the loop. We cover scope in detail in the functions lesson β€” for now, just know that not every variable is visible everywhere.

Best Practices

  1. Use descriptive names: totalPrice not tp.
  2. Prefer const over let when the value won't change.
  3. Avoid one-letter names except for very short loops (i, j).
  4. Don't reuse a variable for two unrelated purposes β€” make a new one.
  5. Initialize variables when you declare them. Empty/uninitialized variables cause subtle bugs.

Common Mistakes

  • Confusing = with ==: = assigns; == compares. Mixing them up is the most common beginner bug.
  • Reassigning a constant: trying to change a const in JavaScript or final in Java throws an error.
  • Using a variable before it's declared: in some languages this is an error; in others, you get a silent bug.
  • Mutating shared state by accident: changing a variable that another part of the code relied on.
  • Picking unclear names: data, info, thing tell readers nothing.

Variable Visualizer

Pick a scenario and step through it. Each box is a variable; the contents flash when they change.

πŸ›
See the bugs in action

We have a dedicated Common Bugs with Variables page β€” five real broken snippets with the fix. Read it before you start writing.

Quick Quiz

Real-World Uses (Production Code, Today)

Game state

A platformer game keeps let lives = 3. Each death decrements it. When it hits 0 the game ends. That's the same idea as the very first variable you ever write.

Login form

When you log in, the site stores your session as a variable: const session = { userId: 42, expires: ... }. Reading session.userId is exactly what we did with our box-with-a-label.

Shopping cart

An e-commerce site holds your cart as let items = [...]. Every "add to cart" mutates this variable. Same pattern, real consequences.

Frequently Asked Questions

What's the difference between let, const, and var in JavaScript?

let creates a block-scoped variable you can reassign. const creates a block-scoped variable that can't be reassigned. var is older, function-scoped, and rarely used in modern code β€” prefer let and const.

Does Python have constants?

Not enforced by the language, but by convention. Naming a variable in UPPER_SNAKE_CASE (like MAX_RETRIES) signals "do not reassign." Some libraries enforce constants more strictly via typing.Final.

Why does Java make me declare the type?

Java is statically typed: every variable's type is known at compile time, which catches certain errors before the program runs. Python and JavaScript are dynamically typed β€” types are checked while running. Both approaches have trade-offs.

What happens if I read a variable I never set?

JavaScript: returns undefined (silently β€” bug-prone). Python: raises a NameError. Java: refuses to compile. Always initialize variables when declaring them.

What is "shadowing"?

When a new variable inside a smaller scope (like a function) reuses the name of an outer variable. The inner one "shadows" the outer one. It's legal but easy to confuse β€” avoid it where possible.

How many variables can I have in a program?

Practically unlimited (millions, easily). In practice, a function with more than ~7 variables is hard to read β€” break it up.

What's a "global" variable?

A variable declared at the top level of a file, accessible from anywhere in that file (or even other files, depending on the language). Global variables are convenient but cause hard-to-track bugs β€” use sparingly.

Should I use shorter or longer variable names?

Long enough to be clear, short enough to read. userEmailAddress is fine; theEmailAddressOfTheCurrentlyLoggedInUser is excessive. email is often perfect.

βœ…
Key takeaways
  • A variable = a name + a value.
  • Use const / final / ALL_CAPS for things that don't change.
  • Pick descriptive names; case matters.
  • Always initialize when declaring.
Was this helpful?
M
Mark Sullivan
Lead writer Β· 8 yrs full-stack

Mark started coding in 2017 after switching from financial analysis. She's built production systems in Python (Django) and JavaScript (Node + React) at two startups, and has taught intro programming at his local community college since 2022. He owns the curriculum for variables, functions, conditionals, and loops on this site. More about Mark β†’