JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 2: Variables, Values and TypesLesson 6 of 150About 40 minutes

Lesson 6: Variables with let and const

01Opening question

A shopping cart remembers how many items you chose while you keep browsing. Where does a program keep a value it needs later?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Run it. productName never changes, so it is a const. quantity changes from 1 to 3, so it is a let.

const productName = "Desk lamp";
let quantity = 1;
quantity = quantity + 2;
console.log(productName, quantity);

03Objective and prerequisites

Learning objective: Declare variables with let and const, choose between them, reassign let variables safely and name variables so code explains itself.

You need: Lesson 5: Reading errors and developing a programming mindset

Skills practised: Values and variables, Variables and constants.

04Explanation

A variable is a named place that stores a value so you can use it later. You create one with a declaration: let score = 10; creates a variable called score and puts 10 in it.

Use const for values that will not be replaced, such as a price or a product name. Use let for values that change, such as a running total or a counter. Start with const and switch to let only when you need to reassign.

To change a let variable, assign a new value without the keyword: score = score + 5;. Writing let score a second time in the same place is an error, and assigning to a const is an error too.

Good names say what the value means: itemCount is better than x. JavaScript names are case-sensitive (total and Total are different), cannot start with a digit and cannot contain spaces. The usual style is camelCase.

05Definitions

Variable
A named storage place for a value.
Declaration
The statement that creates a variable, such as let count = 0;.
Assignment
Putting a new value into an existing variable with =.
let
Declares a variable that can be reassigned.
const
Declares a variable that cannot be reassigned.
camelCase
A naming style that joins words and capitalises each word after the first: cartTotal.

Open the full glossary

06Visual learning object

Variable value explorer. Step through declarations and assignments and watch each variable's box change.

Loading the interactive object…

Open the full Variable value explorer page with its guided experiment.

07Examples

ex-006-01let changes, const stays Browser-executable JavaScript

The price is fixed, so it is a const. The quantity changes, so it is a let and is reassigned without the keyword.

const price = 12;
let quantity = 2;
console.log("Quantity:", quantity, "Total:", price * quantity);
quantity = 5;
console.log("Quantity:", quantity, "Total:", price * quantity);
Sample input
None
Expected output
Quantity: 2 Total: 24 Quantity: 5 Total: 60
Common mistake
Writing let quantity = 5; again instead of quantity = 5;.
Try this
Add a third change that sets quantity to 10 and prints the new total.
Source
examples/ex-006-01-let-and-const.js

ex-006-02A running total Browser-executable JavaScript

A let variable can grow step by step. Each assignment reads the old value and stores a new one.

let total = 0;
total = total + 25;
total = total + 40;
total += 15;            // shorthand for total = total + 15
console.log("Cart total:", total);
Sample input
None
Expected output
Cart total: 80
Common mistake
Forgetting to start total at 0, which gives NaN (undefined + 25).
Try this
Add a line that removes 25 with -=.
Source
examples/ex-006-02-running-total.js

ex-006-03Assigning to a const Browser-executable JavaScript

Assigning to a const stops the program with a TypeError. Everything before that line has already run.

const taxRate = 0.1;
console.log("Tax rate:", taxRate);
taxRate = 0.2;
console.log("This line never runs");
Sample input
None
Expected output
Tax rate: 0.1 Uncaught TypeError: Assignment to constant variable.
Common mistake
Using const for a value that must change. Choose let instead.
Try this
Change the declaration so the program runs to the end.
Source
examples/ex-006-03-const-cannot-change.js

ex-006-04Names that explain themselves Browser-executable JavaScript

Both programs compute the same thing. The second one can be read without any comments.

const a = 3;
const b = 4.5;
console.log(a * b);

const notebookCount = 3;
const notebookPrice = 4.5;
const notebookTotal = notebookCount * notebookPrice;
console.log("Notebook total:", notebookTotal);
Sample input
None
Expected output
13.5 Notebook total: 13.5
Common mistake
Using one-letter names everywhere, which makes later changes risky.
Try this
Rename the first two variables to meaningful names.
Source
examples/ex-006-04-good-names.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Choose let or const

Decide which variables must be let and which can be const.

let storeName = "Corner Shop";
let visitors = 0;
visitors = visitors + 1;
visitors = visitors + 1;
console.log(storeName, "visitors:", visitors);

Track the score

Reassign a let variable with compound assignment.

let score = 0;
// TODO: add 10 points for a correct answer
// TODO: add 10 points for another correct answer
// TODO: subtract 5 points for a hint
console.log("Score:", score);

Parking meter

Design variables for a small calculation from a description.

// A parking meter charges 2.5 per hour.
// A driver parks for 3 hours, then extends by 2 more hours.

09Prediction

Commit to an answer first, then run the real code to compare.

let level = 1;
const bonus = 2;
level = level + bonus;
level = level * bonus;
console.log(level);

What does this print?

10Debugging investigation

The loyalty points never increase

A loyalty program should add 50 points per purchase. After three purchases the balance still shows 100.

let points = 100;
points + 50;
points + 50;
points + 50;
console.log("Points:", points);

More cases in the Debugging Detective Laboratory

11Practical scenario

A cart that remembers

The Shopping Cart keeps product prices in constants and the quantities in variables that change as the shopper clicks. Stage 1 of the project uses exactly this split.

const priceA = 25;
let qtyA = 0;
qtyA += 2;
console.log("A:", qtyA, "line total:", priceA * qtyA);

12Knowledge check

1. What does this print?

let x = 5;
x = x + 3;
console.log(x);
  • 5
  • 8
  • 3
  • An error

2. Why does this stop with an error?

const rate = 3;
rate = 4;
  • const values cannot be printed
  • A const cannot be reassigned
  • rate must be a string
  • The semicolon is missing

3. Which declaration fits a counter that goes up each time a button is clicked?

  • const clicks = 0;
  • let clicks = 0;
  • clicks = 0;
  • var const clicks = 0;

4. Which is a valid variable name?

  • 2ndPlace
  • cart total
  • cartTotal
  • let

5. What does this print?

let total = 10;
total += 2;
console.log(total);
  • 10
  • 12
  • 2
  • NaN

6. Both versions print 30. Which is easier to maintain?

  • A: const a = 10; const b = 3; console.log(a * b);
  • B: const unitPrice = 10; const units = 3; console.log(unitPrice * units);
  • They are equally clear
  • Neither works

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Choose let or const: Prints the visitor count; storeName is declared with const; visitors is still a let
  • Track the score: Prints Score: 15; score holds 15; Uses += and -=
  • Parking meter: Prints hours and cost; ratePerHour is a const of 2.5; hours ends at 5; The cost is calculated
  • ex-006-01: output matches the documented expected output
  • ex-006-02: output matches the documented expected output
  • ex-006-03: output matches the documented expected output
  • ex-006-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-02-variables-values-and-types/lesson-006-variables-with-let-and-const/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • A variable stores a value under a name.
  • Use const by default and let when the value must change.
  • Reassign with = (or +=, -=) and without the keyword.
  • Choose names that explain the value; JavaScript is case-sensitive.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation let versus const
Context: I am learning let and const in JavaScript.
Task: Explain when to use each with three examples from a shopping cart.
Constraints: Beginner level, no var, no objects.
Expected behaviour: I can choose the right keyword for any simple variable.
Testing: End with four declarations for me to classify, answers hidden at the bottom.
Code review Review my variable names
Context: I wrote a 10-line parking cost program.
Task: Suggest clearer names for my variables and explain why each is better.
Constraints: Do not change the logic. Keep camelCase.
Expected behaviour: Every name says what its value means.
Testing: List old name → new name so I can rename and rerun.
Debugging Assignment to constant
Context: My program stops with TypeError: Assignment to constant variable.
Task: Help me find which line causes it by asking questions.
Constraints: Do not rewrite the program.
Expected behaviour: I can explain why the error happens and fix it myself.
Testing: Ask me to run it again after each change.
Exercise generation Variable drills
Context: I finished the parking meter exercise.
Task: Create two more small calculation exercises that need both let and const.
Constraints: Give exact expected output for each.
Expected behaviour: Each exercise has one value that changes.
Testing: Include the expected output to compare with mine.
Code prediction Reassignment chain
Context: I can follow simple assignments.
Task: Give me five short programs that reassign let variables and ask what they print.
Constraints: Integers only, at most four lines each.
Expected behaviour: Each has one exact answer.
Testing: Reveal the answers only after I reply.