A variable is a named container that stores a value. Think of it as a labeled box: you give it a name, put something inside, and can read or change what is inside at any time. Almost every line of JavaScript you write will create, read, or update a variable.
Creating a variable is called declaring it. JavaScript gives you four ways to do it. Modern code uses the first two; you still need to recognize the other two because you will see them in older code and tutorials.
| Way | Example | Era | Use it? |
|---|---|---|---|
let |
let x = 5; |
Modern (2015+) | Yes, for values that change |
const |
const x = 5; |
Modern (2015+) | Yes, your default choice |
var |
var x = 5; |
Older (before 2015) | No, recognize it only |
| automatic | x = 5; |
Older | Never |
All four create a variable named x holding 5. The differences are about safety: whether the value can change, where the variable is visible, and whether JavaScript will warn you about mistakes. Each one is covered below.
Declaring a variable tells JavaScript the name exists. Until you give it a value, it holds undefined, JavaScript's way of saying "the box exists but it is empty":
let carName; // declared, no value yet
console.log(carName);
carName = "Volvo"; // assigned later
console.log(carName);
Most of the time you declare and assign in one line. This is called initializing the variable:
let score = 0; // number
let player = "Alex"; // string
let active = true; // boolean
console.log(score, player, active);
In JavaScript the equal sign = is the assignment operator. It does not mean "is equal to" like it does in math. It means: work out the value on the right, then store it in the variable on the left.
That is why this line, which makes no sense in algebra, is perfectly normal code:
let x = 5;
x = x + 5;
console.log(x);
Read x = x + 5 right to left, in two steps:
count = count + 1; run three times, logging count after each one. Say out loud what each step does, reading right to leftconst MAX = 100; and then MAX = 200;. Run it and read the error"1" + 2 + 3 and 1 + 2 + "3". Explain why they differlet total = 5; then totl = 50; then log total. Notice there is no error. Now add "use strict"; as the very first line and run it againThe left side of = must always be a variable. 5 = x is an error because you cannot store something inside the number 5.
== or ===, not =. x = 5 puts 5 into x. x === 5 asks "is x equal to 5?" and gives back true or false. Mixing these up is one of the most common beginner bugs. Comparisons get their own lesson in JS Comparisons.
Because assignment replaces the old value, a let variable can be updated as often as you like:
let lives = 3;
console.log(lives); // 3
lives = 2;
console.log(lives); // 2
lives = lives - 1;
console.log(lives); // 1
x += 5 means x = x + 5. You will meet the full set in the JS Assignment lesson.
Use const when the value should never be replaced, and let when it needs to change. Here is a small shopping example mixing both:
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
console.log(total);
total = total + 2; // fine: let allows reassignment
console.log(total);
price1 = 10; // ERROR: const cannot be reassigned
The prices are fixed, so they are const. The total changes as things are added, so it is let. A const must also be given its value on the same line it is declared: const rate; on its own is a SyntaxError.
The next two lessons (JS Let and JS Const) go deeper into each one, including block scope and what "cannot be changed" really means for arrays and objects.
If you assign to a name that was never declared, JavaScript quietly creates the variable for you. No let, const, or var needed:
x = 5; // never declared
y = 6;
z = x + y;
console.log(z);
It works, so why is it a bad idea? Two reasons:
score but type scroe = 10, JavaScript does not complain. It silently creates a brand new variable called scroe, and your real score never changes. That kind of bug can take a long time to find.let score = 0;
scroe = 10; // typo: creates a new variable, no error
console.log(score);
"use strict";, automatic variables are not allowed. Assigning to an undeclared name throws ReferenceError: scroe is not defined, which points you straight at the typo. JavaScript modules and classes are always in strict mode. Either way, the habit to build is simple: always declare your variables.
var was the only way to declare a variable before 2015, so you will see it all over older code, Stack Overflow answers, and tutorials:
var x = 5;
var y = 6;
var z = x + y;
console.log(z);
It looks just like let, but it follows older, looser rules: it ignores block boundaries like if and loop braces, and it lets you declare the same name twice without an error. let and const were added to fix exactly those problems. When you meet var in someone else's code, read it as "an older let". When you write new code, use let or const instead.
const if the value should not be changedconst for arrays and objects too (you can still change what is inside them; you just cannot replace the whole thing)let only when you know the value must changevarconst cart = []; // the cart itself stays the same array
cart.push("apple"); // but you can add to it
console.log(cart);
A variable's name is called its identifier. Names can be short like x or descriptive like totalScore. Descriptive is almost always better. The rules:
_, and dollar signs $_, or $ (never a digit, so JavaScript can tell names apart from numbers)color and Color are two different variableslet, if, return, and class cannot be used as nameslet color = "blue";
let Color = "red"; // a separate variable
console.log(color, Color);
JavaScript treats _ and $ as if they were letters, so all of these are valid:
let _lastName = "Johnson";
let _100 = 5;
let $myMoney = 5;
let $ = "Hello";
Each has a convention among programmers. A leading underscore usually signals "private, for internal use only". A $ is often used by libraries as a short alias for their main function (jQuery's $() is the famous example), and some developers start names with $ when they hold a page element.
// Invalid names
let 1stPlace; // starts with a digit
let my-score; // hyphen reads as minus
let const; // reserved keyword
firstName, totalScore, isLoggedIn. Values that are true constants for the whole program (a tax rate, a max size) are often written in UPPER_SNAKE_CASE: const TAX_RATE = 0.08;
Variables can hold several types of data. Types get a full lesson soon (JS Types); for now, the two you need are numbers and strings (text).
3.14, 200"John Doe", 'Yes I am!'"3.14" is textconst pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
console.log(typeof pi);
console.log(typeof "3.14");
The quotes matter a lot, as the next section shows.
With numbers, + adds. With strings, + joins them together, which is called concatenation:
let sum = 5 + 2 + 3;
let name = "John" + " " + "Doe";
console.log(sum);
console.log(name);
When you mix a string and a number with +, JavaScript turns the number into a string and joins them. It works left to right, so where the string sits changes the answer:
let a = "5" + 2 + 3;
let b = 2 + 3 + "5";
console.log(a);
console.log(b);
"5" + 2 + 3: the string comes first, so "5" + 2 is "52", then "52" + 3 is "523"2 + 3 + "5": the numbers come first, so 2 + 3 is 5, then 5 + "5" is "55""3" + 4 gives "34", not 7. You will learn how to convert strings to numbers in JS Type Conversion.
You can declare several variables in one statement. Start with let or const once and separate the variables with commas:
let person = "Ana", age = 16, city = "Boston";
A single declaration can also span several lines, which is easier to read:
let person = "Ana",
age = 16,
city = "Boston";
let person = "Ana"; then let age = 16;) is what most style guides prefer. Each line is easier to read, comment, and move around. Know the comma form so you can read it, but you do not need to write it.
What does this log?
let coins = 10;
coins = coins * 2;
coins = coins + 5;
console.log(coins);
25. Read each line right to left: 10 * 2 is 20, stored in coins. Then 20 + 5 is 25, stored in coins. Each assignment replaces the old value.What do these log?
console.log("7" + 1 + 1);
console.log(7 + 1 + "1");
711 and 81. JavaScript works left to right. In the first, the string comes first, so everything after it is joined: "71", then "711". In the second, 7 + 1 is added to 8 before the string appears, then joined: "81".What does this log, and is there an error?
let highScore = 0;
highscore = 500;
console.log(highScore);
0, with no error. highscore (lowercase s) is a different name, so line 2 silently creates a new automatic variable instead of updating highScore. In strict mode it would throw ReferenceError: highscore is not defined and point you straight at the typo.let count = 0, then run count = count + 1 three times. Say out loud what each step does, reading right to leftconst MAX = 100 then try MAX = 200. Read the error message"1" + 2 + 3 and 1 + 2 + "3". Explain why they differlet total = 5; then totl = 50; then log total. Notice there is no error. Now run "use strict"; tottal = 1; and compare