Complete JavaScript Course Module 2: Beginner: Variables and Data Types

JavaScript Variables: let, const and var Explained

  • Beginner
  • Lesson 2.1
  • 6 min read
  • 4 of 76 in the course

In short

JavaScript variables store values so you can use them later. Learn how to declare variables with let and const, why to avoid var, and how to name them well. What is a variable in JavaScript? A variable is a named container for a value. Imagine a cardboard box with a label on it.

JavaScript variables store values so you can use them later. Learn how to declare variables with let and const, why to avoid var, and how to name them well.

What is a variable in JavaScript?

A variable is a named container for a value. Imagine a cardboard box with a label on it. The label is the variable's name, for example username. Inside the box is the value, for example 'Sara'. Whenever you need the value, you just use the label.

Programs use variables all the time: to remember the user's name, the number of items in a shopping cart, the score in a game, or whether someone is logged in.

const username = 'Sara';
let cartItems = 3;

console.log(username);
// Output: Sara
console.log(cartItems);
// Output: 3

Line by line:

  • const username = 'Sara'; creates a box labelled username and puts the text 'Sara' inside.
  • let cartItems = 3; creates a box labelled cartItems and puts the number 3 inside.
  • console.log(username) looks inside the box and prints what it finds.

Declaring, assigning and reassigning variables

Three words you will hear a lot:

  • Declaring a variable means creating it: let score;
  • Assigning a value means putting something inside it with the = sign: score = 0;
  • Reassigning means replacing the value with a new one: score = 10;

You can declare and assign in one step, which is the most common way: let score = 0;

In JavaScript, = does not mean "is equal to" like in math. It means "put the value on the right into the variable on the left".

let score = 0;
console.log(score);
// Output: 0

score = 10;
console.log(score);
// Output: 10

score = score + 5;
console.log(score);
// Output: 15

let nickname;
console.log(nickname);
// Output: undefined

The line score = score + 5; can look strange at first. JavaScript first works out the right side (the current score, 10, plus 5 equals 15), then stores the result back in score. Notice also that nickname was declared but never given a value, so it holds undefined, which means "no value yet".

Common mistake: Writing let again when you reassign. Writing let score = 10; a second time causes SyntaxError: Identifier 'score' has already been declared. Use let only once, when you create the variable. After that, write just score = 10;.

let vs const: use const by default

JavaScript has two modern keywords for variables:

  • const (short for constant) creates a variable that cannot be reassigned. Once the box is filled, you can't swap the value for a different one.
  • let creates a variable that can be reassigned later.
const birthYear = 1998;
let age = 27;

age = 28;          // fine, age was made with let
console.log(age);
// Output: 28

birthYear = 2000;  // error!
Uncaught TypeError: Assignment to constant variable.

A good rule used by most developers: use const by default, and switch to let only when you know the value will change, such as a counter or a score. This makes your code safer and easier to read. When someone sees const, they know that value stays the same in the rest of the code.

A const must also get a value right away. Writing const total; on its own is a SyntaxError.

Note: const stops you from putting a new value in the box. Later in the course you'll see that the contents of a const list or object can still be changed. That's normal and allowed.

Why you should not use var

Before 2015, JavaScript had only one keyword for variables: var. You will still see it in old tutorials and old code. Modern JavaScript replaced it with let and const because var has confusing behaviors:

  • You can declare the same var twice by accident, and JavaScript won't warn you.
  • A var can be used before the line where it is declared (it gives undefined instead of an error), which hides bugs.
  • A var ignores most curly-brace blocks { }, so it can "leak" out of places where you expected it to stay.
var color = 'red';
var color = 'blue';   // no error, the first value is silently replaced
console.log(color);
// Output: blue

With let or const, the second line would give a clear error and help you find the mistake. So: recognize var when you see it, but write let and const in your own code.

Variable naming rules and camelCase

JavaScript has some strict rules for names:

  • Names can contain letters, digits, _ and $.
  • Names cannot start with a digit. 2ndPlace is not allowed; secondPlace is.
  • Names cannot contain spaces or hyphens. user-name is not allowed.
  • Names are case-sensitive: score and Score are two different variables.
  • You can't use reserved words such as let, const, if, return or class.

On top of the rules, there is a style that almost all JavaScript developers follow: camelCase. You write the first word in lowercase and start every next word with a capital letter, like the humps of a camel: firstName, totalPrice, isLoggedIn.

NameAllowed?Good style?
firstNameYesYes, camelCase
first_nameYesWorks, but not the usual JavaScript style
first nameNoContains a space
1stNameNoStarts with a digit
xYesNo, it doesn't say what it stores
const productName = 'Wireless Headphones';
const productPrice = 59.99;
let isInStock = true;

console.log(productName, productPrice, isInStock);
// Output: Wireless Headphones 59.99 true

These names tell you exactly what each box contains. Good names are like good labels on moving boxes: anyone can find what they need.

Tip: Name true/false variables like a yes/no question: isOpen, hasAccount, canEdit. You'll understand them instantly when you read your code later.

Practice exercise

Create variables for a simple online order: the customer's name, the product name, the price of one item and the quantity. Use const for values that won't change and let for the quantity. Log a sentence about the order. Then change the quantity and log the new total price.

Hint: the total is price * quantity. Because the quantity changes, it must be declared with let.

Key takeaways

  • A variable is a labelled box that stores a value.
  • Use const by default and let only when the value needs to change.
  • Avoid var in new code; it has confusing behaviors.
  • In JavaScript, = means "store this value", not "is equal to".
  • Use clear camelCase names like totalPrice and isLoggedIn.

Frequently asked questions

What is the difference between let and const in JavaScript?

A variable made with let can get a new value later. A variable made with const cannot be reassigned after it is created. Use const when the value stays the same and let for values like counters.

Should I ever use var?

Not in new code. let and const do everything var did, with fewer surprises. You only need to recognize var when reading older code.

Can a JavaScript variable change its type?

Yes. A let variable that holds a number can later hold text. JavaScript allows this, but it usually makes code harder to follow, so try to keep one kind of value per variable.