Skip to content
aviral gupta

// B1.2 · ~30 min · Beginner

Variables with let and const

After this lesson you can store values with let and const, change a let variable, and fix the errors from reassigning a const, using a name too early or declaring it twice.

Lesson 2 of 5 in B1 Getting started

You will be able to

  • Declare a variable with let, reassign it, and predict what it holds
  • Choose between let and const, and read the TypeError from reassigning a const
  • Name variables by the rules, and fix errors from using a name too early or declaring it twice
  1. Warm-up · Activity 1 of 7

    Warm-up: which line creates a variable called score that holds 0?

  2. Predict · Activity 2 of 7

    Predict before you read on: what does this print?

    let lives = 3;
    lives = lives - 1;
    console.log(lives);
  3. Practice · Activity 3 of 7

    Fill in the keyword so that the program runs and prints 12.

    ____ count = 10;
    count = count + 2;
    console.log(count);
    count = 10;
  4. Practice · Activity 4 of 7

    Which kind of error does this program stop with?

    const price = 4;
    price = 5;
    console.log(price);
  5. Practice · Activity 5 of 7

    Match each program to what running it gives.

  6. Brain teaser · Activity 6 of 7

    Brain teaser. What does this program print?

    let total = 10;
    console.log(total);
    let total = 20;
    console.log(total);
  7. Apply · Activity 7 of 7

    Mini-task. Write a step counter. Declare a daily goal of 10000 steps and a step count that starts at 0. Add three walks of 2500, 4000 and 3000 steps, printing the count after each one, then print how many steps are left to the goal. Decide for each variable whether it is const or let.

    Check your work against this list

Build it yourself

Read the worked example, then write the exercises. Your code runs in your browser or on your computer and is never uploaded.

Worked example

Keeping score in a small game

This program follows one round of a game. The player’s name and the points per coin never change, so they are const. The score and the lives change as the round goes on, so they are let. Run it, then try to reassign pointsPerCoin and read the error.

main.js

// One round of a game, tracked with const and let.
const player = "Ada";
const pointsPerCoin = 10;
let score = 0;
let lives = 3;
console.log(player, "starts with", score, "points and", lives, "lives");
score = score + 3 * pointsPerCoin;
console.log("After 3 coins:", score);
lives = lives - 1;
console.log("Hit! Lives left:", lives);
score = score + 5 * pointsPerCoin;
console.log("After 5 more coins:", score);
console.log(player, "ends with", score, "points");

Run it with

node main.js

Output

Ada starts with 0 points and 3 lives
After 3 coins: 30
Hit! Lives left: 2
After 5 more coins: 80
Ada ends with 80 points
  • score is reassigned twice; each time the right side uses its current value.
  • The lines that change score and lives have no let: the variables already exist.
  • pointsPerCoin is const, so writing pointsPerCoin = 20; would stop the program with a TypeError.
  • The names are in lower camel case: pointsPerCoin, not pointspercoin or points_per_coin.
Change it and run it

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.

Exercises

Exercise 1 of 2

A shopping budget

You have a budget of 50 and buy three things: 12.5, then 20, then 7.5. After each purchase add its price to spent and print the new total, as Spent: 12.5 and so on. Finally print what is left of the budget, as Left: 10. Work everything out with the variables; do not type the results.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.

Hints
  1. Hint 1

    spent = spent + 12.5; adds the first price to what was spent so far.

  2. Hint 2

    Print after each purchase: console.log("Spent:", spent);

  3. Hint 3

    What is left is budget - spent, worked out on the last line.

Show a solution

One way to solve it. Yours can look different and still pass the checks.

const budget = 50;
let spent = 0;
spent = spent + 12.5;
console.log("Spent:", spent);
spent = spent + 20;
console.log("Spent:", spent);
spent = spent + 7.5;
console.log("Spent:", spent);
console.log("Left:", budget - spent);
Run it on your computer

Install ECMAScript 2026 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.js

const budget = 50;
let spent = 0;
// Add each price to spent and print it: 12.5, then 20, then 7.5.
// Then print what is left of the budget.

main.test.js

import {test} from 'node:test';
import assert from 'node:assert/strict';
import {runMain} from './learnrun.js';

const lines = async () => (await runMain()).trimEnd().split('\n');

test('prints four lines', async () => {
  const got = await lines();
  assert.equal(got.length, 4, `the program printed ${got.length} line(s), expected 4`);
});

test('prints the total after each purchase', async () => {
  const got = await lines();
  assert.deepEqual(got.slice(0, 3), ['Spent: 12.5', 'Spent: 32.5', 'Spent: 40'], `the first three lines are ${JSON.stringify(got.slice(0, 3))}`);
});

test('prints what is left', async () => {
  const got = await lines();
  assert.equal(got[3], 'Left: 10', `the fourth line is ${JSON.stringify(got[3])}, expected "Left: 10"`);
});

package.json

{
  "type": "module"
}

package.json tells Node.js that the .js files are modules; keep it in the folder.

Run the program:

node main.js

Run the checks (needs learnrun.js in the same folder):

node --test
Download learnrun.js

Exercise 2 of 2

Fix the weather report

This program should print Berlin 12, then Berlin 14, then Hamburg 14, but it stops with an error. Run it, read the error, fix that line and run it again: there are three mistakes, each giving a different kind of error. Keep the order of the lines.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.

Hints
  1. Hint 1

    The first error is a SyntaxError: a name is declared twice. To change a variable, leave out let.

  2. Hint 2

    Names are case-sensitive: temperature and Temperature are different names.

  3. Hint 3

    A variable that gets a new value later must be declared with let, not const.

Show a solution

One way to solve it. Yours can look different and still pass the checks.

let city = "Berlin";
let temperature = 12;
console.log(city, temperature);
temperature = temperature + 3;
temperature = temperature - 1;
console.log(city, temperature);
city = "Hamburg";
console.log(city, temperature);
Run it on your computer

Install ECMAScript 2026 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.js

const city = "Berlin";
let temperature = 12;
console.log(city, temperature);
temperature = temperature + 3;
let temperature = temperature - 1;
console.log(city, Temperature);
city = "Hamburg";
console.log(city, temperature);

main.test.js

import {test} from 'node:test';
import assert from 'node:assert/strict';
import {runMain} from './learnrun.js';

test('runs without an error', async () => {
  await runMain();
});

test('prints the three reports', async () => {
  const got = (await runMain()).trimEnd().split('\n');
  assert.deepEqual(got, ['Berlin 12', 'Berlin 14', 'Hamburg 14'], `the program printed ${JSON.stringify(got)}`);
});

package.json

{
  "type": "module"
}

package.json tells Node.js that the .js files are modules; keep it in the folder.

Run the program:

node main.js

Run the checks (needs learnrun.js in the same folder):

node --test
Download learnrun.js

Common mistakes

Reassigning a const

const lives = 3;
lives = lives - 1;
console.log(lives);

What Node.js prints

TypeError: Assignment to constant variable.

Why, and the fix

A const always keeps the value it was declared with, so line 2 stops the program. If the value really has to change, declare it with let: let lives = 3;. If it should not change, the mistake is on line 2: store the new value under a new name instead, such as const livesLeft = lives - 1;.

Using a variable above its declaration

console.log(total);
let total = 5;

What Node.js prints

ReferenceError: Cannot access 'total' before initialization

Why, and the fix

A program runs top to bottom, and a let or const can be used only once its line has run. The message is different from total is not defined: JavaScript knows the name, but it has no value yet. Move the declaration above the first line that uses it.

Declaring the same name twice

let score = 0;
console.log(score);
let score = 10;
console.log(score);

What Node.js prints

SyntaxError: Identifier 'score' has already been declared

Why, and the fix

let creates a variable; it does not change one. A second let with the same name is a SyntaxError, so the file cannot be read and not even line 2 prints. To give score a new value, write score = 10; without let.

JavaScript in the browser: your browser’s own engine, in a sandboxed worker. Syntax errors are located with acorn 8.18.0, MIT. Licence and source

Exit ticket

5 questions, no hints. Score 80% or more to complete the lesson.

Finish every activity above to unlock the exit ticket.

Report a problem

Spotted something wrong or unclear? Say what, and it will be checked and fixed.

#

At least 20 characters.

Only if you want a reply.

Key ideas

A variable is a name for a value

let score = 0; declares a variable called score and gives it the value 0. Later, score = score + 10; reassigns it: JavaScript works out the right side first, using the old value, then stores the result, so score becomes 10. There is no let on that line, because the variable already exists. let score; on its own declares a variable with no value yet, and printing it shows undefined. Use a variable by its name, without quotes: console.log(score) prints 10, console.log("score") prints the word score.

const: a name that never gets a new value

const rate = 0.19; declares a constant. It needs its value on the same line: const rate; stops with SyntaxError: Missing initializer in const declaration. Giving it a new value later stops the program with TypeError: Assignment to constant variable. MDN’s rule is: use const when you can, and use let when you have to. So a birth year is const and an age that changes is let. You will also meet var in older code. It is the original keyword, and MDN calls its design confusing and error-prone, so this course does not use it.

Names, and the order of lines

A name may contain letters, digits, _ and $, but must not start with a digit: const 1st = 2; is a SyntaxError. Names are case-sensitive, so score and Score are two variables, and words of the language such as for, class or new cannot be names. The usual style is lower camel case: firstName, totalPrice. A let or const exists only from its line on: using it above that line stops with ReferenceError: Cannot access 'total' before initialization. Declaring the same name twice is a SyntaxError, so no line of the file runs.

Sources

Last reviewed September 30, 2026