Course outline · 0% complete

0/29 lessons0%

Course overview →

let and const

lesson 2-1 · ~8 min · 4/29

Quiz

Warm-up from lesson 1-3: you printed a sentence with a template literal. Which characters wrap a template literal?

Two ways to declare a variable

In Python a variable appears the moment you assign it: score = 10. JavaScript makes you declare it first, and gives you two keywords:

  • let declares a variable you may reassign later.
  • const declares a variable you may never reassign. The name is locked to its value.
let score = 10;
score = 15;        // fine

const name = "Ada";
name = "Grace";    // TypeError! const cannot be reassigned

The professional habit: use const by default, and switch to let only when you actually need to reassign (counters, running totals). This tells every reader which values can change.

You may also see var in old tutorials. It is the pre-2015 keyword with confusing scope rules. Modern code does not use it, and neither will we.

let score1015reassign okconst name"Ada"locked, no reassignment
A let variable can point at a new value later. A const variable is locked to its first value forever.

Code exercise · javascript

Run this. score changes over time, so it is let. The greeting never changes, so it is const.

Code exercise · javascript

Your turn. This program crashes with TypeError: Assignment to constant variable. Fix the declaration so the reassignment is allowed and the program prints 10.

Quiz

You are declaring a variable for a shopping total that grows as items are added. Which keyword fits?