A variable is a named container that stores a value so you can use it later. Your score in a game, a visitor's name and the items in a shopping basket are all stored in variables.
Variables are the starting point for almost everything else in programming. Calculations, decisions and loops all work by reading values from variables and storing new values in them. Modern JavaScript gives you two keywords for creating variables, let and const, and choosing between them is simpler than it first looks.
Creating variables with let and const
let score = 0;
const playerName = "Mia";letcreates a variable whose value can change later, as inscore = 10.constcreates a variable that can't be reassigned. Use it for values that stay the same.- The
=sign here means "store this value in the variable". It doesn't mean "equals" as it does in maths.
Creating a variable is called declaring it. You only declare a variable once; after that you use its name without let or const.
Should you use let or const?
Use const by default. Switch to let only when you know you'll reassign the variable, such as a counter or a running total. This makes your code easier to read, because anyone can see at a glance which values change.
You'll see var in older code and tutorials. It has confusing scope rules (see Scope) and allows mistakes that let and const prevent, so don't use it in new code.
Variable naming rules
- Names can contain letters, digits,
_and$, but can't start with a digit. - Names are case-sensitive:
ageandAgeare different variables. - You can't use reserved words such as
let,classorreturn. - The convention is camelCase:
firstName,totalPrice,isLoggedIn. - Choose names that explain the value:
daysUntilBirthdayis far clearer thand.
Good names are one of the easiest ways to make code understandable. Variables that hold true or false often start with is or has, such as isOpen or hasDiscount.
Variables without a value
If you declare a variable with let but don't give it a value, it holds undefined:
let winner;
console.log(winner); // undefinedThat's useful when the value isn't known yet, for example until a game finishes. A const must always be given a value straight away, because it can never be assigned later.
JavaScript Variables Syntax
Declaring variables
const name = "value"; // can't be reassigned
let count = 0; // can change
count = count + 1; // reassign (no let this time)
let empty; // declared, value is undefinedJavaScript Variables Summary
- A variable stores a value under a name so you can use it later.
- Use
constby default andletwhen the value needs to change. - Avoid
varin new code. - Names are case-sensitive, can't start with a digit and use camelCase by convention.
- A
letvariable without a value holdsundefined; aconstneeds a value immediately.
JavaScript Variables Examples
Each example runs in the page. Edit the code and press Run to see what changes.
Changing values with let
let lives = 3;
console.log("Lives:", lives);
lives = lives - 1;
console.log("Ouch! Lives:", lives);
lives = lives - 1;
console.log("Careful! Lives:", lives);Line-by-line explanation
- Line 1Create
liveswith the value 3. - Line 4Reassign it: take the current value, subtract 1 and store the result. There's no
let, because the variable already exists. - Line 7Again: now it's 1.
const in a shopping basket
const shopName = "Sprout Grocers";
const basket = ["bread", "milk"];
basket.push("eggs");
console.log(shopName);
console.log(basket);Line-by-line explanation
- Line 1A shop's name won't change, so
const. - Line 2The basket variable will always point to the same array…
- Line 4…but we can still add items inside it.
conststops reassignment, not changes to contents.
Variables working together
const firstName = "Ada";
const lastName = "Lovelace";
const birthYear = 1815;
const thisYear = 2026;
const fullName = firstName + " " + lastName;
const age = thisYear - birthYear;
console.log(fullName, "would be", age, "years old.");Line-by-line explanation
- Lines 1 to 4Four values in four well-named constants.
- Line 6Join strings with
+and a space in between. - Line 7Calculate with numbers.
- Line 9Combine everything in one log.
Common JavaScript Variables Mistakes
Reassigning a const
const speed = 50;
speed = 60; // TypeError: Assignment to constant variable.let speed = 50;
speed = 60;If a value needs to change, declare it with let.
Declaring the same variable twice
let points = 10;
let points = 20; // SyntaxError: already declaredlet points = 10;
points = 20;Use let once to create, then plain = to update.
Using a variable before it exists
console.log(total); // ReferenceError
let total = 100;let total = 100;
console.log(total);Code runs from top to bottom, so create the variable first.
JavaScript Variables in Real Projects
Variables are everywhere
A to-do app stores tasks; a game stores score, level and isPaused; a shop stores cartItems and deliveryFee. Good variable names are one of the biggest differences between code that's easy to work with and code nobody wants to touch.
JavaScript Variables Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Create a constant for the planet and a variable for the day count, then add one day.
planet = "Mars";
days = 1;
days = days + 1;
console.log(planet, days);
planet never changes (const); days is reassigned (let).What does this print?
let x = 5;
x = x + 10;
x = x * 2;
console.log(x);Which variable name is valid and follows the convention?
What happens?
const colors = ["red"];
colors.push("blue");
console.log(colors);push changes the array's contents; the variable still points to the same array.The counter should go from 0 to 2 and print Clicks: 2. Fix the declarations.
const clicks = 0;
clicks = clicks + 1;
let clicks = clicks + 1;
console.log("Clicks:", clicks);- Logs "Clicks: 2"
- No errors
JavaScript Variables Quiz
3 questions to check what you learned.
Which keyword should you use by default?
- var
- const
- let
- variable
What is the value of a variable declared with
let x;and nothing else?- 0
- null
- ""
- undefined
Are
scoreandScorethe same variable?- Yes
- No, because JavaScript is case-sensitive
- Only if declared with var
- Only inside functions
JavaScript Variables Challenge
Trip budget
Using variables:
- A
constnamedbudgetset to500 - A
letnamedspentstarting at0 - Add
120(hotel) and then45(food) tospentin two separate statements - A
constnamedleftequal tobudget - spent - Log
Left to spend: 335
- budget is 500
- spent ends at 165
- left is 335
- Logs "Left to spend: 335"