Back
LearnJavaScript From ZeroWhy do we need variables?

Why do we need variables?

2 min read

A program with a bad memory is useless

Imagine you ask a friend to remember your phone number, and every time you ask for it, they say "what number?". Useless, right? A program needs memory too. That memory is called a variable.

A variable is just a labelled box where you keep a value, so you can use it again later.

How do we make one?

let age = 25;

Read it like a sentence: "let age be 25". Now the word age holds the value 25. Anywhere you write age, JavaScript reads 25.

let name = "Aisha";
console.log(name);          // shows: Aisha
console.log("Hi " + name);  // shows: Hi Aisha

What is the difference between let and const?

You will see two words for making variables: let and const.

  • let → a box whose value can change later.
  • const → a box whose value is fixed — it can never change.
let score = 0;
score = 10;      // ok, score is allowed to change

const pi = 3.14;
pi = 4;          // error! const cannot change

So which one should I use?

Here is a simple rule that good developers actually follow: use const by default. Only switch to let when you know the value will change (like a score going up).

Why? Because const quietly protects you. If you ever try to change something that was not meant to change, JavaScript warns you straight away, instead of letting a silent bug slip in.

One-line memory: a variable is a labelled box. const is a locked box, let is a box you can refill.

Next, let us look at what kinds of things you can actually put inside these boxes.

Tip