Codiqo

Learn JavaScript · lesson 3 of 60 · about 7 minutes

Variables with let and const

Store a value once under a name, use it all over your page, and update it when it changes.

What you'll learn

  • Store a value in a const
  • Use a variable more than once
  • Change a value with let

Write it once

Your name appears in the heading and again at the bottom of your page. Change it in one place and forget the other, and the page contradicts itself. Store it once, in a variable, and use the variable everywhere.

const name = "Ada"; makes a variable called name holding "Ada". + joins strings together.

One variable, used in two places

const name = "Ada";
document.querySelector("#greeting").textContent = "Hello, " + name + "!";
document.querySelector("#footer").textContent = "Made by " + name;

let can change, const can't

Some values change while the program runs: a score, a count of clicks. Make those with let, then give them a new value with =.

A const can't be given a new value: trying stops the program with a TypeError. Use const unless you know the value will change.

Step through it to watch the score change

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

Output

15

Tip

Name variables after what they hold, in camelCase: firstName, totalPrice. No spaces, and a name can't start with a number.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.