LEARN TO CODE | JAVASCRIPT | 01 LANGUAGE FOUNDATIONS
01.2 Variables: let and const
Declare named values, choose let or const deliberately and trace how a value changes as statements execute.
01 | WHY DOES A PROGRAM NEED NAMES?
A game needs to remember a score. A shop needs a ticket price. A quiz needs a player name. Repeating literal values everywhere would make the program awkward to understand and change.
A variable is a named binding to a value. For a first mental picture, think of a label that lets the program find the value it is currently using. The label is the identifier; 10 or "Alex" is the value.
When the score changes, later statements read the new value. JavaScript does not rewrite the earlier console output or automatically recalculate every value previously derived from it.
Keep index.html and script.js in the same VS Code folder. Put the current example into script.js, save it, open or refresh index.html in your browser and look in that page’s Developer Tools Console.
Replace the previous example unless a task explicitly says to add to it. Pasting several independent examples together can redeclare the same let or const name. The downloadable examples use a separate folder for each complete program.
02 | DECLARE AND INITIALISE
let score = 0;
console.log(score);
let declares the name score. = assigns the initial value 0. Declaring means introducing the name; initialising means giving it its first value.
The name is not in quotes when you want its value. console.log(score) reads the variable, while console.log("score") prints the literal word score.
TRY IT YOURSELF
Predict console.log("score") and console.log(score) after let score = 12.
Reveal guidance
The first logs score as text. The second logs 12, the current value associated with the name.
03 | UPDATE WITH ASSIGNMENT
let score = 0;
score = 10;
score = 25;
console.log(score);
Use let once when introducing the name. Later assignment statements use the existing name without another let. Each assignment replaces the value associated with that variable.
= means assignment, not the mathematical claim that two expressions are permanently equal. JavaScript evaluates the right-hand expression, then assigns that result to the left-hand variable.
The program logs 25 because that is the value at the moment console.log runs. It does not log all previous assignments unless you explicitly add logging after them.
04 | READ SCORE = SCORE + 5 CAREFULLY
let score = 10;
score = score + 5;
console.log(score);
| Step | What happens |
|---|---|
| 1. Read the right-hand side | Read the current score: 10 |
| 2. Calculate | 10 + 5 gives 15 |
| 3. Assign | Replace score with 15 |
| 4. Continue | Later reads of score use 15 |
We write score = score + 5 because we want to keep the old score and add to it . score = 5 would discard the old total and replace it with 5.
The right-hand score means the old value at this statement. The left-hand score names where the result should go. This is why the statement is useful in a program even though it would look strange as an algebraic equation.
05 | USE CONST WHEN YOU WILL NOT REASSIGN
const pointsPerGoal = 3;
let goals = 2;
console.log(goals * pointsPerGoal);
goals = 4;
console.log(goals * pointsPerGoal);
const declares a binding that cannot be reassigned. pointsPerGoal stays attached to its initial value, while goals can be assigned a different value with let.
A const declaration needs its initial value immediately. Use const by default when the program does not need reassignment; use let when changing the binding is part of the design.
const does not mean “known before the program runs”. It can hold a result calculated at runtime. For arrays and objects, const prevents reassignment of the binding, not changes to their contents; later lessons explore that distinction.
TRY IT YOURSELF
Should a fixed ticket price and a running total use the same declaration keyword?
Reveal guidance
A fixed ticket price can use const. A total repeatedly assigned a new value needs let. The decision is about reassignment, not whether the value is a number or text.
06 | A DECLARATION IS NOT AN UPDATE
Declaring the same let name twice in the same scope is an error. If score already exists, use score = 20 rather than let score = 20. Scope means the region of code in which a name is available.
The browser Console can retain declarations during a session, and developer tools differ in how they handle repeated console declarations. For dependable practice, save one complete example in script.js and reload the page.
Using let and const also means you should declare a name before reading it. Do not rely on assigning to an undeclared name and hoping JavaScript creates it for you.
07 | CHOOSE NAMES THAT CARRY MEANING
| Good choice | Why |
|---|---|
| playerName | Describes the value |
| remainingLives | Explains what the number represents |
| totalPrice | More informative than x in a shop program |
| score2 | Digits can follow the first character |
Use letters, digits after the first character, underscores or dollar signs in these beginner identifiers. Do not use spaces, hyphens or reserved words such as let as variable names. student-name would be read as subtraction, not as one name.
camelCase joins words by capitalising each word after the first: pointsPerRound. JavaScript is case-sensitive, so playerName and playername are different names.
There are broader Unicode naming rules, but simple descriptive English identifiers keep these examples easy to read and type.
08 | SHORTER UPDATES, SAME IDEA
let coins = 10;
coins += 4;
coins -= 2;
coins++;
console.log(coins);
coins += 4 adds 4 to the existing numeric value. coins -= 2 subtracts 2. coins++ increases the numeric value by 1. We use increment as a separate statement here, avoiding the extra rules about the value of an increment expression.
Trace this program as 10, then 14, then 12, then 13. Shorter syntax is helpful only when you understand the longer assignment it represents.
TRY IT YOURSELF
Start with 20 points, gain 7, then spend 5. Log the final value using numeric updates.
Reveal guidance
Use let points = 20; points += 7; points -= 5; console.log(points);. The result is 22.
09 | VALUES ARE NOT LIVE FORMULAS
let ticketCount = 2;
const ticketPrice = 6;
let totalPrice = ticketCount * ticketPrice;
ticketCount = 3;
console.log(totalPrice);
totalPrice = ticketCount * ticketPrice;
console.log(totalPrice);
The first calculation stores 12 in totalPrice. Changing ticketCount afterwards does not re-run that earlier statement. The first log therefore still shows 12.
The later assignment explicitly calculates again using the current ticketCount, producing 18. Variables store values; an assignment does not automatically create a live spreadsheet-style formula.
10 | A COMPLETE SCOREBOARD EXAMPLE
const playerName = "Alex";
const pointsPerWin = 5;
let wins = 0;
let score = 0;
wins += 1;
score = wins * pointsPerWin;
console.log(playerName);
console.log(score);
wins += 1;
score = wins * pointsPerWin;
console.log(score);
The name and points-per-win rule stay the same during this run. wins and score are reassigned as the game progresses. Logging after each calculation makes the changing state visible.
State means the values the program currently holds. Tracing state statement by statement is one of the most useful habits you can develop.
11 | A FIRST LOOK AT BLOCK SCOPE
const clubName = "Robotics";
{
const sessionNumber = 1;
console.log(clubName);
console.log(sessionNumber);
}
console.log(clubName);
A pair of curly braces creates a block here. sessionNumber is declared inside that block, so it is not available after the closing brace. clubName is declared outside it and is available inside the nested block.
You will soon see braces around conditions and loops. Keeping values close to the code that needs them helps prevent accidental changes elsewhere. We use let and const throughout rather than introducing the older var rules now.
TRY IT YOURSELF
Explain why a changing score uses let, and why changing score does not change an earlier logged result.
Reveal guidance
let allows reassignment. Each console.log reads and prints the value when it executes; earlier primitive-number output is not recalculated when the variable changes.
KEEP LEARNING
Previous page 01.3 Data types, operators and template literals
Download Section 01 example programs
Further reading: JavaScript in VS Code · Grammar and types · Template literals · Loops and iteration