Variables with let and const
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- 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.
constcreates a variable that cannot be given a new value.letcreates 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,classorreturn. - Names are case sensitive, so
ageandAgeare two different variables.
The conventions most developers follow:
- Use camelCase:
firstName,totalPrice,isLoggedIn. - Make names describe the content.
priceis better thanp.userCountis better thanx. - Start yes/no values with a verb such as
isorhas: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 = 5with 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 withage = 21. - Believing const means deeply constant. As shown above, the contents of an array or object can still change.
Try it yourself
- Declare a
constfor your name and aletfor your age. Increase the age by one and print both. - Create variables
widthandheight, and aconst areathat multiplies them. Print the result. - Try to reassign a
constand read the error message. - Rename these bad names to better ones:
x,d,temp2,flag. Think about what each might hold.
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