Learn by reading through in order

let and const — Controlling Reassignment and Redeclaration

Choose between const and let for variable declarations, covering reassignment, redeclaration, and camelCase naming.

Whether you're totaling an order or displaying the logged-in user's name, you need to give a value a name so you can reference it repeatedly. That name is a variable (a name attached to a value — write the name, and you get the same value back).

JavaScript gives you two ways to create a variable, const and let, and which one you pick decides whether you can swap in a different value later.

Naming a Value — Choosing Between const and let

Write the same value directly in multiple places in your code, and you'll have to hunt down every occurrence when it needs to change. Give values like a unit price or tax rate a name up front, and reference that name from then on.

The line where you name it is called a declaration (the line that creates a variable's name and gives it its first value).

A JavaScript declaration decides, at the same time it creates the name, whether that name's contents can be swapped out later. Use const if not, let if so.

Putting a different value into an existing name is called reassignment (giving an already-declared name a different value later on). A name declared with const can't be reassigned, so a useful default is to write const first, and switch to let only when a line comes up that needs to reassign it.

What const and let Can Do
Declaration typeReassignnew value inRedeclaresame name againconstNoTypeErrorNoSyntaxErrorletYesNoSyntaxError
Reassignment (putting a different value into the same name) — only let can do it. Redeclaration (declaring the same name again) — neither can. What TypeError and SyntaxError are is covered in the next section.

const — For Values You Won't Swap Out

const fixes a value on the line where you declare it, and that name never takes a different value after that. Things like a product name, unit price, or tax rate — values that stay the same as processing continues — fit here, and most values in a program do.

A sequence of characters wrapped in quotes, like "Insulated Mug", is called a string, and a number like 1200 is a number. Both are covered in detail in articles 3 and 4.

console.log, which shows up in the next code example, is the instruction that prints whatever value you pass it, in parentheses, to the results screen as text. This site's console has no screen, so you pass it any value you want to check.

Everything from // to the end of the line is a comment (explanatory text left in the code that never runs) and won't appear in the output. Lines like // ① that appear pre-written in exercises are this same kind of note.

// Values you won't swap out use const
const productName = "Insulated Mug";
const unitPrice = 1200;

console.log(productName);   // Insulated Mug
console.log(unitPrice);     // 1200

Store a single online store product in variables and display it.

① Declare productName as "Insulated Mug", unitPrice as 1200, and quantity as 3, all with const.

② Display the contents of productName.

③ Calculate the subtotal from the unit price and quantity, and display it.

(If it runs correctly, an explanation will appear.)

JavaScript / TypeScript Editor

Run code to see output

let — Variables You'll Swap Values Into Later

Use let for things like a stock count or running total — values whose contents change as processing continues. The right side of = reads the current value as-is, so you can read the current value, calculate with it, and reassign the result back to the same name.

let orderTotal = 0;

orderTotal = orderTotal + 1200;  // Read the current 0, add 1200, reassign
orderTotal = orderTotal + 400;   // Read the current 1200, add 400, reassign

console.log(orderTotal);         // 1600

A warehouse's stock count changes with every shipment and delivery. stockCount is already declared with let.

① After a shipment reduces stock by 3, reassign the new count to stockCount and display it.

② Then, after a delivery adds 10, reassign the new count to stockCount and display it.

JavaScript / TypeScript Editor

Run code to see output

Reassignment vs Redeclaration — Two Errors That Stop Execution

Choosing const means deciding, right there in the code, that this name's contents never change.

Assign it a different value after that, and JavaScript stops execution on that line and throws a TypeError (an error for using a value the wrong way). Nothing after that line runs.

What Happens When You Assign After Declaring
const price= 1200Name bindsto valueShows 1200price = 1500Stops rightthereTypeErrorlet quantity = 2quantity = 3Binding movesto new valueShows 3tries to assign
The top 2 rows are one flow for const; the bottom row is the flow for let. const stops on the assignment line; let just moves on to the next line.

The other way to stop execution is redeclaration (declaring an already-used name again in the same scope). Neither const nor let allows it — you get a SyntaxError (an error for code that doesn't follow the language's grammar at all).

This catches typos in names, or a name accidentally reused for something else, right away.

let cartQuantity = 1;
let cartQuantity = 2;
// SyntaxError: Identifier 'cartQuantity' has already been declared

If all you want is to swap in a value, declare it only once, then assign to the name on every line after that. A line with no declaration keyword is a reassignment, so with let it won't stop execution.

let itemQuantity = 1;

itemQuantity = 2;            // No declaration keyword, so this is a reassignment
console.log(itemQuantity);   // 2

The Errors Show Up at Different Times

The TypeError from reassignment shows up on that line, once execution gets there — so whatever ran before it still shows in the output.

The SyntaxError from redeclaration shows up while the code is being parsed, so nothing runs, not even line 1. If you see no output at all, suspect a syntax error first.

Values that don't change, like a tax rate, get declared with const. The code below tries to reassign that tax rate afterward. Run it as-is and check how far it gets and what message stops it. (This time you just run the code and read the result — no editing.)

JavaScript / TypeScript Editor

Run code to see output

Naming Variables — camelCase and Allowed Characters

A variable name is where you tell the reader what the value actually is. Names like a or data send you back to the declaration every time you read a distant line. Names like unitPrice or stockCount let the contents be read straight off the name.

Names can use letters, digits, underscores, and the dollar sign, and can't start with a digit. Case matters, so stockcount and stockCount are different variables.

Words JavaScript already assigns meaning to, like const / let / if (reserved words), can't be used as names.

Variable NameAllowed / Not AllowedReason
stockCountAllowedLetters only
item2PriceAllowedA digit mid-name is fine if it starts with a letter
_draftOrderAllowedStarting with an underscore is fine too
$priceAllowedThe dollar sign can be used in names too
2ndItemNot allowedCan't start with a digit
item-priceNot allowedA hyphen is indistinguishable from subtraction
constNot allowedReserved words can't be used as names

For names made of two or more words, use camelCase (start the first word lowercase, capitalize only the first letter of each word after that). priceWithTax or orderTotal are this shape.

JavaScript's built-in functions and properties follow the same shape, so matching it keeps your own names from standing out.

const listPrice = 1250;
const discountRate = 0.15;                 // 15% member discount

// The name tells you what this amount is
const discountedPrice = listPrice * (1 - discountRate);
console.log(discountedPrice);              // 1062.5

// Round down anything under a dollar
console.log(Math.floor(discountedPrice));  // 1062

Work out the total for 2 units of a food item taxed at the reduced 8% rate. unitPrice, quantity, and taxRate are already declared.

① Store the subtotal before tax in a variable with a camelCase name.

② Store the tax-inclusive price — the subtotal with tax applied — in a different camelCase name, and display it.

JavaScript / TypeScript Editor

Run code to see output

Why Not var

Older code and older tutorials introduce a third declaration, var. var lets you redeclare the same name any number of times, doesn't error if you reference it before its declaration line, and just proceeds with a value that hasn't been set yet. The scope where a name is valid also works differently from const / let.

Because it doesn't flag mistakes on the spot, tracking down the cause takes longer.

New Code Doesn't Use var

const and let both flag redeclaration and references before declaration as errors. This course doesn't use var from here on either. The full mechanics of scope itself are covered in the scope article in the syntax category.

This article covered naming values with const and let, the TypeError from reassigning a const, the SyntaxError from redeclaration, and naming rules including camelCase. Values you won't swap out use const; only values you will use let — that choice carries through every piece of code from here on.

QUIZ

Knowledge Check

Answer each question one by one.

Q1Which declaration do you use for a variable you don't plan to reassign after declaring it?

Q2What happens when you run this code?
const unitPrice = 1200;
unitPrice = 1500;
console.log(unitPrice);

Q3Which of these can't be used as a variable name?