A variable is like a named box where you can store information in your computer program. You can put numbers, text, or other data into this box. Then, you use the box's name to get that information back whenever you need it.
JavaScript Variables
JavaScript Variables
A variable is a storage place in your computer's memory. You give this storage place a name. Then, you can put a value into it, like a number or some text. Later, you can use the variable's name to read that value or even change it.
Variables are super important because they help your programs remember things. Imagine a game needs to remember a player's score. It uses a variable for that. When the player earns points, the variable's value changes.
In JavaScript, you declare (create) variables using special keywords: let, const, and var. Each keyword has slightly different rules for how the variable works.
What is a Variable?
A variable is a named container that holds a value. You can store data like numbers, text, or true/false statements inside it.
let
Use let when the value stored in the variable might change later. This is for flexible data.
const
Use const when the value will never change after it's first set. This makes your code safer.
var
This is an older way to declare variables. Modern JavaScript mostly uses let and const instead.
Naming Rules
Variable names must follow specific rules, like starting with a letter, dollar sign, or underscore.
Declaring Your First Variable
Declaring Your First Variable
To create a variable, you choose one of the keywords (let, const, or var). Then you write the name you want for your variable. After that, you use an equals sign (=) to put a value into your variable. This process is called declaration and assignment.
The equals sign here does not mean "is equal to" like in math. It means "store this value into this variable". Once declared, you can use the variable's name to work with its value.
1// Declare a variable named 'score' using 'let'2// Assign the number 0 to 'score'3let score = 0;45// Declare a constant variable named 'userName' using 'const'6// Assign the text 'Guest' to 'userName'7const userName = 'Guest';89// Print the current value of 'score' to the console10console.log(score); // Output: 01112// Print the current value of 'userName' to the console13console.log(userName); // Output: Guest1415// You can change the value of a 'let' variable16score = 100; // Now 'score' holds the number 10017console.log(score); // Output: 100
Always declare your variables first!
If you try to use a variable name before you declare it with let or const, JavaScript will give you an error. The computer needs to know about the box before you try to put something in it or take something out.
console.log(playerLives); // ❌ ReferenceError: playerLives is not defined
let playerLives = 3;
How Variables Store Values
How Variables Store Values
When you declare a variable like let gameLevel = 1, JavaScript finds a small space in your computer's memory. It labels that space with the name gameLevel and puts the number 1 inside it.
If you later write gameLevel = 2, JavaScript goes back to that same memory space. It removes the old value (1) and puts the new value (2) in its place. This is how let variables can change over time.
For const variables, like const MAX_LEVEL = 10, JavaScript also finds a memory space and puts the value 10 inside. But this time, it locks that space. You cannot put a different value into a const variable after its first assignment.
1// Using 'let' for a variable that changes2let playerCount = 5;3console.log('Initial players:', playerCount); // Output: Initial players: 545// We can change the value of 'playerCount'6playerCount = 6;7console.log('New players:', playerCount); // Output: New players: 689// Using 'const' for a variable that stays the same10const GAME_TITLE = 'Space Explorer';11console.log('Game Title:', GAME_TITLE); // Output: Game Title: Space Explorer1213// If we try to change a 'const' variable, it will cause an error!14// GAME_TITLE = 'Galaxy Quest'; // ❌ This line would cause a TypeError
const gameScore = 0;gameScore = 100; // ❌ TypeError: Assignment to constant variable.console.log(gameScore);
let gameScore = 0;gameScore = 100; // ✅ This works perfectly.console.log(gameScore); // Output: 100
let vs const — Which One to Use?
let vs const — Which One to Use?
Choosing between let and const is a very common decision in JavaScript. The main rule is simple: use const if the value in the variable will never change. Use let if you expect the value to be updated later in your code.
Most programmers like to use const as much as possible. This is because it makes your code safer. If a variable should not change, const prevents you from accidentally changing it later. This helps avoid bugs.
// Use 'let' for things that updatelet currentHealth = 100; // Player's healthcurrentHealth = currentHealth - 10; // Health goes downlet loopCounter = 0; // A counter in a looploopCounter = loopCounter + 1; // Counter increaseslet userName = 'player1'; // User can change their nameuserName = 'newPlayerName';
// Use 'const' for things that are fixedconst MAX_HEALTH = 100; // Max health never changesconst GRAVITY = 9.8; // Gravity is a constant valueconst GAME_VERSION = '1.0.0'; // Game version is fixed for this build// 'const' also works for objects and arrays,// preventing the whole object/array from being replacedconst playerSettings = { volume: 50, difficulty: 'easy' };
// Use 'let' for things that updatelet currentHealth = 100; // Player's healthcurrentHealth = currentHealth - 10; // Health goes downlet loopCounter = 0; // A counter in a looploopCounter = loopCounter + 1; // Counter increaseslet userName = 'player1'; // User can change their nameuserName = 'newPlayerName';
// Use 'const' for things that are fixedconst MAX_HEALTH = 100; // Max health never changesconst GRAVITY = 9.8; // Gravity is a constant valueconst GAME_VERSION = '1.0.0'; // Game version is fixed for this build// 'const' also works for objects and arrays,// preventing the whole object/array from being replacedconst playerSettings = { volume: 50, difficulty: 'easy' };
The 'Prefer const' Rule
A good habit is to always start by declaring variables with const. If you later find you need to change its value, then you can switch it to let. This helps keep your code robust and less prone to errors.
Using Variables in a Real Program
Using Variables in a Real Program
Variables are the building blocks of almost every program. They allow you to store user input, calculate results, and keep track of your program's state. For example, a simple online store might use variables for item prices, quantities, and a total cost.
Choosing clear and descriptive names for your variables is also very important. A variable named itemPrice is much easier to understand than a variable named x.
Set up fixed values with const
First, declare any values that will not change, like an item's base price or a tax rate. Use const for these.
1const itemPrice = 50;2const salesTaxRate = 0.05; // 5%
Calculate dynamic values with let
Next, use let for values that are calculated or might change, such as the quantity or the final total.
1let quantity = 2;2let subtotal = itemPrice * quantity; // 50 * 2 = 100
Apply calculations to update values
Now, perform calculations and update your let variables. Here, we calculate the tax and then the total.
1let taxAmount = subtotal * salesTaxRate; // 100 * 0.05 = 52let totalAmount = subtotal + taxAmount; // 100 + 5 = 105
Display the final result
Finally, use console.log() to show the result to the user or for debugging.
1console.log('Subtotal: $' + subtotal);2console.log('Tax: $' + taxAmount);3console.log('Total: $' + totalAmount);
Avoid accidental global variables
If you forget to use let, const, or var when you assign a value (e.g., myVariable = 10; instead of let myVariable = 10;), JavaScript might create a global variable. Global variables can be changed from anywhere in your code and often lead to hard-to-find bugs. Always use let or const to declare your variables explicitly.
Variable Keywords Compared
Variable Keywords Compared
| Keyword | Can Reassign? | Scope | When to Use |
|---|---|---|---|
| let | Yes | Block scope | For values that will change (e.g., counters, user input, calculated results) |
| const | No | Block scope | For values that should never change (e.g., fixed settings, API URLs, mathematical constants) |
| var | Yes | Function scope | Avoid for new code; it has confusing behavior. Seen in older JavaScript. |
Test Your Knowledge
Test Your Knowledge
Which keyword should you use for a variable whose value will change throughout your program?
What happens if you try to change the value of a const variable after it has been declared?
Which of the following is NOT a valid JavaScript variable name?
What is the primary reason modern JavaScript developers prefer let and const over var?
Quick Reference
Quick Reference
- 1Variable — a named container in memory used to store data, like numbers or text.
- 2
let— use this keyword to declare variables whose values you expect to change later in the program. - 3
const— use this keyword to declare variables whose values should remain fixed and never change after their initial assignment. - 4
var— an older keyword for declaring variables; it has different scoping rules and is generally avoided in new JavaScript code. - 5Prefer
const— a good practice is to start by declaring all variables withconstand only switch toletif you truly need to reassign its value. - 6Naming Rules — variable names must start with a letter,
_, or$. They cannot start with a number or contain spaces. - 7Case-Sensitive —
score,Score, andSCOREare treated as three completely different variables by JavaScript. - 8Declare Before Use — always declare a variable with
letorconstbefore you try to use its value to avoid errors. - 9No Undeclared Globals — always use
letorconstwhen assigning a value; never just writemyVar = 5;to prevent creating accidental global variables. - 10Assignment Operator (
=) — the equals sign assigns a value to a variable, it does not check for equality like in mathematics.
Variable Scope
Dive deeper into how block scope and function scope control variable visibility.
Data Types
Explore the different kinds of values variables can hold, such as strings, numbers, and booleans.
Operators
Learn how to perform calculations and comparisons using variables with JavaScript operators.
Functions
Understand how variables are used within functions and how data is passed between them.
You now understand JavaScript Variables!
You've successfully learned how to create and use variables with let and const, understood why var is less common, and explored how variables store and manage data in your programs. This fundamental knowledge is crucial for building any interactive web application!
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.