JavaScript Variables

Store values in named boxes with let and const.

Lesson 4 of 56Beginner14 min read

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

JavaScript
let score = 0;
const playerName = "Mia";
  • let creates a variable whose value can change later, as in score = 10.
  • const creates 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: age and Age are different variables.
  • You can't use reserved words such as let, class or return.
  • The convention is camelCase: firstName, totalPrice, isLoggedIn.
  • Choose names that explain the value: daysUntilBirthday is far clearer than d.

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:

JavaScript
let winner;
console.log(winner); // undefined

That'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 undefined

JavaScript Variables Summary

  • A variable stores a value under a name so you can use it later.
  • Use const by default and let when the value needs to change.
  • Avoid var in new code.
  • Names are case-sensitive, can't start with a digit and use camelCase by convention.
  • A let variable without a value holds undefined; a const needs a value immediately.

JavaScript Variables Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

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);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 1Create lives with the value 3.
  2. Line 4Reassign it: take the current value, subtract 1 and store the result. There's no let, because the variable already exists.
  3. Line 7Again: now it's 1.
Example 2

const in a shopping basket

const shopName = "Sprout Grocers";
const basket = ["bread", "milk"];

basket.push("eggs");

console.log(shopName);
console.log(basket);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 1A shop's name won't change, so const.
  2. Line 2The basket variable will always point to the same array…
  3. Line 4…but we can still add items inside it. const stops reassignment, not changes to contents.
Example 3

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.");
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 1 to 4Four values in four well-named constants.
  2. Line 6Join strings with + and a space in between.
  3. Line 7Calculate with numbers.
  4. Line 9Combine everything in one log.

Common JavaScript Variables Mistakes

Reassigning a const

Don't
const speed = 50;
speed = 60; // TypeError: Assignment to constant variable.
Do
let speed = 50;
speed = 60;

If a value needs to change, declare it with let.

Declaring the same variable twice

Don't
let points = 10;
let points = 20; // SyntaxError: already declared
Do
let points = 10;
points = 20;

Use let once to create, then plain = to update.

Using a variable before it exists

Don't
console.log(total); // ReferenceError
let total = 100;
Do
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.

Fill in the blankseasy

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);
Predict the outputeasy

What does this print?

let x = 5;
x = x + 10;
x = x * 2;
console.log(x);
Multiple choicemedium

Which variable name is valid and follows the convention?

Predict the outputmedium

What happens?

const colors = ["red"];
colors.push("blue");
console.log(colors);
Fix the bugmedium

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);
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Clicks: 2"
  • No errors

JavaScript Variables Quiz

3 questions to check what you learned.

  1. Which keyword should you use by default?

    • var
    • const
    • let
    • variable
  2. What is the value of a variable declared with let x; and nothing else?

    • 0
    • null
    • ""
    • undefined
  3. Are score and Score the same variable?

    • Yes
    • No, because JavaScript is case-sensitive
    • Only if declared with var
    • Only inside functions

JavaScript Variables Challenge

Trip budget

Using variables:

  1. A const named budget set to 500
  2. A let named spent starting at 0
  3. Add 120 (hotel) and then 45 (food) to spent in two separate statements
  4. A const named left equal to budget - spent
  5. Log Left to spend: 335
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • budget is 500
  • spent ends at 165
  • left is 335
  • Logs "Left to spend: 335"