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 labelledusernameand puts the text'Sara'inside.let cartItems = 3;creates a box labelledcartItemsand puts the number3inside.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
letagain when you reassign. Writinglet score = 10;a second time causesSyntaxError: Identifier 'score' has already been declared. Useletonly once, when you create the variable. After that, write justscore = 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.letcreates 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:
conststops you from putting a new value in the box. Later in the course you'll see that the contents of aconstlist 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
vartwice by accident, and JavaScript won't warn you. - A
varcan be used before the line where it is declared (it givesundefinedinstead of an error), which hides bugs. - A
varignores 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.
2ndPlaceis not allowed;secondPlaceis. - Names cannot contain spaces or hyphens.
user-nameis not allowed. - Names are case-sensitive:
scoreandScoreare two different variables. - You can't use reserved words such as
let,const,if,returnorclass.
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.
| Name | Allowed? | Good style? |
|---|---|---|
firstName | Yes | Yes, camelCase |
first_name | Yes | Works, but not the usual JavaScript style |
first name | No | Contains a space |
1stName | No | Starts with a digit |
x | Yes | No, 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
constby default andletonly when the value needs to change. - Avoid
varin new code; it has confusing behaviors. - In JavaScript,
=means "store this value", not "is equal to". - Use clear camelCase names like
totalPriceandisLoggedIn.
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.