Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 3 of 58

Variables: let, const and var

Store and reuse values with let and const, learn the naming rules, understand block scope, and see why modern code avoids var.

12 minGetting startedUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonDeclare variables with const and let, choose good names, change values correctly, and explain why you should avoid var.

After this lesson you will be able to create variables, give them sensible names, change them when needed, and know which of the three keywords, const, let and var, to use.

What a variable is

A variable is a name attached to a value, so that you can use the value again later. Without variables a program could only work with numbers and text typed out directly. With them it can remember things.

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

This prints 15. The first line declares the variable score and gives it the value 10. The second line assigns a new value computed from the old one. The equals sign here does not mean "is equal to" as in maths. It means "store the value on the right in the name on the left".

const: the default choice

Use const for a value that you will not reassign.

javascript
const siteName = "Notes";
siteName = "Other";   // not allowed

Running that second line stops the program with TypeError: Assignment to constant variable. A const must also be given its value on the line where it is declared.

Using const by default makes your code easier to follow, because a reader knows the name always means the same thing. Switch to let only when you find you really need to change the value.

const does not freeze the contents

This surprises many beginners. const protects the name, not what the value contains.

javascript
const tags = ["html"];
tags.push("css");
console.log(tags);   // [ 'html', 'css' ]

That works, because the array itself is changed and tags still points at the same array. Only tags = somethingElse would be refused. Arrays and objects get their own lessons later.

let: for values that change

Use let for a value that has to be reassigned, such as a counter, a running total, or a flag that flips.

javascript
let attempts = 0;
attempts = attempts + 1;
attempts += 1;       // a shorter way to say the same thing
console.log(attempts);   // 2

You can declare a let without a value. It then holds undefined, which means "nothing has been put here yet".

javascript
let nothing;
console.log(nothing);   // undefined

Try the difference

This example shows let changing and const refusing to. The try and catch part catches the error so the page can report it. You will learn that properly in the errors lesson.

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  let lines = [];

  let score = 10;
  score = score + 5;
  lines.push("score is " + score);

  const siteName = "Notes";
  try {
    siteName = "Other";
  } catch (error) {
    lines.push(error.name + ": " + error.message);
  }
  lines.push("siteName is still " + siteName);

  out.textContent = lines.join("\n");
</script>

Naming rules

A name can contain letters, digits, underscores and dollar signs, but:

  • It cannot start with a digit: 2fast is invalid, fast2 is fine.
  • It cannot contain spaces or hyphens: my-name is read as "my minus name".
  • It cannot be a reserved word such as let, class or if.
  • It is case sensitive: total, Total and TOTAL are three different variables.

Conventions matter just as much as rules:

  • Use camelCase for ordinary variables: userName, totalPrice.
  • Use names that say what the value means: itemCount beats x, and isLoggedIn beats flag.
  • Many programmers write true constants such as fixed limits in capitals: MAX_ITEMS. This is a habit, not a rule of the language.

Block scope

A block is the code between a pair of curly braces. Variables made with let and const exist only inside the block where they are declared.

javascript
{
  let inner = 1;
}
console.log(inner);   // ReferenceError: inner is not defined

This is helpful: a variable cannot be touched from places that have no business with it. Scope gets a full lesson later in the course.

And var?

Before 2015, var was the only keyword. It still works and you will see it in older code and tutorials, but it behaves in surprising ways.

javascript
var v = 1;
var v = 2;       // declaring it again is allowed, silently
console.log(v);  // 2

function find() {
  if (true) {
    var leaked = "hi";
  }
  return leaked;   // works: var ignores the braces of the if
}
console.log(find());   // hi

A var is scoped to the whole function, not the block, and it can be redeclared without a warning. Both make mistakes harder to spot. For new code, use const and let and you will never need var.

Common mistakes

  • Using let for everything. If a value never changes, const documents that and lets the language catch accidental changes.
  • Assuming const makes things unchangeable. It only blocks reassignment. An array or object stored in a const can still be edited.
  • Misspelling a name. totl instead of total gives ReferenceError: totl is not defined. Copy names rather than retyping when in doubt.
  • Declaring twice. Writing let count = 1; and later let count = 2; in the same scope is a SyntaxError. Declare once, then assign with count = 2;.
  • Using a variable before it is declared. Reading a let or const above its declaration line throws an error.
  • Starting a name with a digit or adding a hyphen. Use item2 and itemCount.

Exercise

  1. Declare a const called price with the value 20 and a let called quantity with the value 1.
  2. Increase quantity to 3.
  3. Print price * quantity with console.log. You should see 60.
  4. Try to reassign price and read the error message.
  5. Rename each variable to something longer and clearer, and check it still works.

Next: Data types.

Key points

  • A variable is a named place that holds a value, created with let or const.
  • Use const by default, and let only when the value has to be reassigned.
  • const stops reassignment, not change, so the contents of a const array or object can still be modified.
  • let and const are block scoped, while var is function scoped and can leak out of blocks.
  • Names are case sensitive, cannot start with a digit, and by convention use camelCase.

Check yourself

1. What happens when you reassign a const variable?
2. Given const list = [1, 2]; what does list.push(3) do?
3. Where can a variable declared with let inside curly braces be used?
4. Which is a valid variable name?
5. What does a variable declared with let but never given a value contain?

Free tools for this lesson