Tutorials / JavaScript Fundamentals / Variables with let and const

Variables with let and const

12 min read javascript
Course contents (16 lessons)
  1. Getting started
  2. What is JavaScript and where does it run?
  3. Variables with let and const
  4. Values and operators
  5. Data types: numbers, strings, booleans, null and undefined
  6. Operators: arithmetic, comparison and logical
  7. Strings and template literals
  8. Making decisions and repeating work
  9. Conditionals: if, else and switch
  10. Loops: for, while and for...of
  11. Functions
  12. Functions: declarations, parameters and return values
  13. Arrow functions and callbacks
  14. Arrays and objects
  15. Arrays: creating, reading and changing lists
  16. Array methods: map, filter, find and reduce
  17. Objects: properties, methods and copying
  18. Scope and the browser
  19. Scope and closures, gently
  20. The DOM: selecting and changing elements
  21. Events: reacting to clicks, input and forms
  22. Final project
  23. Project: build a to-do list in the browser

What a variable is

A variable is a name that points to a value. You use it so you can write a value once and use it many times, or so you can change it later.

Think of a labelled box. The label is the name and the thing inside is the value. In JavaScript you create a variable with a keyword, a name and an equals sign.

const and let

Modern JavaScript has two main keywords.

  • const creates a variable that cannot be given a new value.
  • let creates a variable that can be changed.
const siteName = "HussoTech";
let visitors = 100;

visitors = visitors + 1;
visitors += 5;

console.log(siteName);
console.log(visitors);

This prints HussoTech and then 106. We start visitors at 100, add 1, then add 5 more. The += form is a short way to write visitors = visitors + 5.

If you try siteName = "Other", JavaScript stops with the error TypeError: Assignment to constant variable. That error is useful. It tells you that you changed something you promised not to change.

Which one should you use?

My habit is simple. Start with const. Change it to let only when you really need to reassign the value. Most variables in real programs never change, so most of mine are const. When you read someone else's code, a const tells you that this name always means the same thing.

What about var?

Older code uses var. You will meet it in old tutorials and old code bases. It works, but it has odd scope rules that cause bugs, and it lets you declare the same name twice without any warning. Do not use it in new code. We will look at scope in a later lesson.

Declaring without a value

You can declare a variable now and assign to it later:

let total;
console.log(total); // undefined
total = 50;
console.log(total); // 50

A let variable with no value holds undefined, which is JavaScript's way of saying "nothing has been put here yet". A const must always get a value at the moment it is declared.

const does not freeze everything

This one confuses many beginners. const stops you from pointing the name at a different value. It does not stop an array or object from being changed inside.

const colours = ["red", "green"];
colours.push("blue");
console.log(colours); // ["red", "green", "blue"]

// colours = ["black"];  // this would throw an error

The name colours still points at the same array. We only added an item to it. Reassigning the name is the thing const prevents. We will come back to this when we cover arrays and objects.

Naming rules and conventions

The rules JavaScript enforces:

  • Names can contain letters, digits, _ and $.
  • A name cannot start with a digit.
  • A name cannot be a reserved word such as let, class or return.
  • Names are case sensitive, so age and Age are two different variables.

The conventions most developers follow:

  • Use camelCase: firstName, totalPrice, isLoggedIn.
  • Make names describe the content. price is better than p. userCount is better than x.
  • Start yes/no values with a verb such as is or has: isActive, hasPermission.
  • Use UPPER_SNAKE_CASE for fixed settings that never change, such as MAX_RETRIES.

Good names save more time than any comment. When I review code, bad names are the first thing that slows me down.

A small worked example

const pricePerItem = 250;
let quantity = 3;
const taxRate = 0.15;

const subtotal = pricePerItem * quantity;
const tax = subtotal * taxRate;
const total = subtotal + tax;

console.log("Subtotal:", subtotal);
console.log("Tax:", tax);
console.log("Total:", total);

Because every name says what it holds, you can read the calculation like a sentence. If quantity changes later, only one line needs an edit.

Common mistakes

  • Using let for everything. It works, but you lose the signal that a value is fixed.
  • Forgetting to declare. Writing count = 5 with no keyword creates an accidental global variable in sloppy-mode scripts. Always declare.
  • Redeclaring. Writing let age = 20; twice in the same scope is a syntax error. Declare once, then assign with age = 21.
  • Believing const means deeply constant. As shown above, the contents of an array or object can still change.

Try it yourself

  1. Declare a const for your name and a let for your age. Increase the age by one and print both.
  2. Create variables width and height, and a const area that multiplies them. Print the result.
  3. Try to reassign a const and read the error message.
  4. Rename these bad names to better ones: x, d, temp2, flag. Think about what each might hold.
javascript
const siteName = "HussoTech";
let visitors = 100;

visitors = visitors + 1;
visitors += 5;

console.log(siteName);
console.log(visitors);

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account