SKU // 08

JavaScript Variables

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.

// Four Ways to Declare 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 and Assigning

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);
undefined Volvo

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);
0 Alex true

// The Assignment Operator

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);
10

Read x = x + 5 right to left, in two steps:

  1. Click Open Playground. Make count = count + 1; run three times, logging count after each one. Say out loud what each step does, reading right to left
  2. Add const MAX = 100; and then MAX = 200;. Run it and read the error
  3. Predict, then check: log "1" + 2 + 3 and 1 + 2 + "3". Explain why they differ
  4. Replace everything with let 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 again

The left side of = must always be a variable. 5 = x is an error because you cannot store something inside the number 5.

Watch out: = is not ==
To compare two values you use == 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
3 2 1
Coming up
Updating a variable using its own value is so common that JavaScript has shortcuts for it: x += 5 means x = x + 5. You will meet the full set in the JS Assignment lesson.

// let and const

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
11 13 TypeError: Assignment to constant variable.

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.

// Automatic Variables (Not Recommended)

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);
11

It works, so why is it a bad idea? Two reasons:

let score = 0;
scroe = 10;                // typo: creates a new variable, no error
console.log(score);
0
Strict mode turns this off
If a script starts with the line "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 (Not Recommended)

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);
11

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.

// When to Use Which

  1. Always declare your variables (never rely on automatic ones)
  2. Use const if the value should not be changed
  3. Use const for arrays and objects too (you can still change what is inside them; you just cannot replace the whole thing)
  4. Use let only when you know the value must change
  5. Avoid var
const cart = [];          // the cart itself stays the same array
cart.push("apple");       // but you can add to it
console.log(cart);
["apple"]

// Naming Rules (Identifiers)

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:

let color = "blue";
let Color = "red";       // a separate variable
console.log(color, Color);
blue red

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
SyntaxError
Convention: camelCase
JavaScript programmers join multi-word names with camelCase: lowercase first word, capital letter to start each word after it. 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;

// Strings and Numbers

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).

const pi     = 3.14;
let   person = "John Doe";
let   answer = 'Yes I am!';

console.log(typeof pi);
console.log(typeof "3.14");
number string

The quotes matter a lot, as the next section shows.

// Arithmetic with Variables

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);
10 John Doe

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);
523 55
Watch out
Anything a user types into a form box arrives as a string, even if it looks like a number. "3" + 4 gives "34", not 7. You will learn how to convert strings to numbers in JS Type Conversion.

// Many Variables in One Statement

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";
Tip
One declaration per line (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.

// Quick Check

What does this log?

let coins = 10;
coins = coins * 2;
coins = coins + 5;
console.log(coins);
Show answer
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");
Show answer
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);
Show answer
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.

// Try It

  1. In the console, declare let count = 0, then run count = count + 1 three times. Say out loud what each step does, reading right to left
  2. Declare const MAX = 100 then try MAX = 200. Read the error message
  3. Predict, then check: "1" + 2 + 3 and 1 + 2 + "3". Explain why they differ
  4. Run let total = 5; then totl = 50; then log total. Notice there is no error. Now run "use strict"; tottal = 1; and compare
// Video Walkthroughs
Last updated: Oct 9, 2026, 11:52 PM ET