A variable is a name that refers to a value in your program, so you can use that value again and change it later. In Python you create one by assigning with =, as in width = 20; in JavaScript you declare it with let or const, as in let width = 20;.
The examples below use Python and JavaScript because both are common first languages and both have official documentation you can check. The idea itself applies to almost every programming language.
What a variable is, in plain terms
MDN describes variables as "symbolic names for values in your application". The name is a label you choose. The value is the data the label points at: a number, a piece of text, a list, and so on.
Without variables you would have to repeat every value each time you need it. With one, you write the value once, give it a name, and use the name everywhere else. If the value changes, you change it in one place.
The Python reference puts it a little more precisely: names refer to objects, and a name is introduced by a binding operation such as an assignment. So in Python, width = 20 means "bind the name width to the value 20".
How to create a variable in Python
The Python tutorial says that the equal sign is used to assign a value to a variable. There is no keyword to declare it first.
width = 20
height = 5 * 9
print(width * height)
Example output:
900
The right-hand side is worked out first (5 * 9 is 45), and then the name on the left is bound to the result. The last line multiplies 20 by 45, which gives 900. This matches the example in the Python tutorial.
How to create a variable in JavaScript
JavaScript makes you declare a variable with a keyword. MDN lists three:
| Keyword | What MDN says it does |
|---|---|
let | Declares a block-scoped variable, optionally initializing it to a value. |
const | Declares a block-scoped variable that cannot be re-assigned, which must be initialized at declaration. |
var | Declares a variable, optionally initializing it to a value. It is local to the function (or global scope), not to the block. |
let width = 20;
const height = 45;
width = 30; // fine: let can be re-assigned
height = 50; // TypeError: Assignment to constant variable.
In new code, use const by default and let when the value has to change. The last line fails because height was declared with const.
A let declaration with no value is allowed. MDN says the variable then holds undefined:
let x;
console.log(x); // undefined
A const declaration with no value is a syntax error: SyntaxError: Missing initializer in const declaration.
Changing a variable's value
The point of a variable is that the value can change while the name stays the same. Assigning again replaces what the name refers to.
score = 0
score = score + 10
score = score + 5
print(score)
Example output:
15
The line score = score + 10 looks odd if you remember algebra, where nothing equals itself plus 10. In code, = is an instruction, not a statement of equality. It reads "work out the right side using the current value, then store the result under the name on the left".
What you can call a variable
Each language has its own rules. For JavaScript, MDN says an identifier usually starts with a letter, an underscore (_) or a dollar sign ($), and later characters can also be digits. Names are case sensitive, so früh and Früh are different variables. MDN's examples of legal names are Number_hits, temp99, $credit and _name.
Python names are case sensitive too, so Total and total are two separate variables. A frequent cause of errors in beginner code is a name spelled one way where it is created and another way where it is used.
Beyond the rules, choose names that say what the value is: order_total tells the next reader more than x does.
Scope: where a variable can be used
A variable is not usable everywhere. Its scope is the part of the program where the name is visible. The Python reference says that if a name is bound in a block, it is a local variable of that block, and if it is bound at the module level, it is a global variable.
def show_total():
total = 100 # local to show_total
print(total)
show_total()
print(total) # NameError: name 'total' is not defined
The final line fails because total only exists inside the function. In JavaScript, let and const work the same way for blocks. MDN's example is a const y declared inside an if block: reading y after the block gives ReferenceError: y is not defined. Variables declared with var are the exception, because they are scoped to the function rather than the block.
Common errors with variables
Using a variable before it exists
The Python tutorial shows what happens if a name has not been assigned:
>>> n
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
In JavaScript, let and const variables cannot be read before the line that declares them. MDN says that doing so always results in a ReferenceError, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
Assigning to a name inside a function
In Python, if a name is assigned anywhere in a function, the whole function treats it as local. The reference says this "can lead to errors when a name is used within a block before it is bound". A function-level example:
count = 10
def add_one():
print(count) # fails: count is local to add_one because of the line below
count = count + 1
add_one()
This raises UnboundLocalError, which the reference describes as a subclass of NameError. The reference notes that exception message wording is not part of the Python API and can change between versions, so read the error name rather than relying on the exact sentence. To change the module-level variable from inside the function, declare it first with global count.
Typos and case
Because names are case sensitive, userName and username are different. If you see "is not defined" for a name you are sure you created, compare the two spellings character by character.
Variables are not the same as environment variables
The phrase is also used for settings that your operating system passes to programs, such as PATH. Those belong to the operating system and the shell, not to a program's own code. If that is what you need, see how to set environment variables on Windows, macOS and Linux.
Frequently asked questions
- What is the difference between a variable and a constant?
- A variable can be given a new value after it is created. A constant cannot. In JavaScript, a name declared with const cannot be re-assigned and must be given a value when it is declared, while a name declared with let can be re-assigned. Python has no keyword that enforces a constant; by convention, names written in capital letters are treated as constants.
- Does a variable store the value or point to it?
- It depends on the language. The Python reference says names refer to objects, so a Python variable is a name bound to a value that lives elsewhere. Other languages, such as C, treat a variable as a named piece of memory that holds the value directly. For everyday code the practical effect is the same: you use the name to get the value.
- What does 'variable is not defined' mean?
- You used a name that the program has not created in the current scope. Python raises NameError: name 'n' is not defined, and JavaScript raises a ReferenceError. The usual causes are a typo, different upper and lower case letters, using the name before assigning it, or using it outside the function or block where it was created.
- Can I change a variable's value to a different kind of value?
- In Python, yes: after x = 5 you can write x = 'five' and the name now refers to text. JavaScript allows the same with let. Some other languages, such as Java and C, require you to declare a type and do not allow the change.