Variables allow to assign values, data, or functions to a reusable named entity.
Think of variables as a box with a declared name, which contains something inside, a value assigned.
There are two ways to define variables in JavaScript: let and const.
(Actually, there is also var coming from previous versions of JavaScript, try not to use it, replace by let, or const if possible)
The first time we define a variable, we must declare it:
let count = 0
const BRAND_COLOR = "#7c6ef7"
count = count + 1 // ✓ let can be reassigned
// BRAND_COLOR = "red" // ✗ TypeError
// avoid var — it's function-scoped, not block-scoped, which causes confusing bugslet
let can be reassigned.
let count = 0
count = count + 1 // ✓ let can be reassignedThis defines a count variable with a value of 0. let allows to reassign count another value. let is only used once for declaration, next time you want to use count variable, it can be directly referenced by its name.
let is particularly useful for variables which need incrementation/decrementation such as counters:
let sum = 0;
sum = sum + 1; // 1
sum += 1; // shorthand operator
sum ++; // shorthand incrementconst
const is fixed after assignment — meaning it can only use once = when variable is defined – use this by default. Both are block-scoped.
const BRAND_COLOR = "#7c6ef7"
// BRAND_COLOR = "red" // ✗ TypeError
// avoid var — it's function-scoped, not block-scoped, which causes confusing bugsAbout const
Something to remember about
constis that while it can only be assigned onceconst=..., its value is not constant or immutable.
Theconstdeclaration creates an immutable reference to a value. The variable identifier cannot be reassigned
The value is not immutable and can be altered
let vs const
How to decide between using const or let?
- Always use
constby default - If you realize variable needs reaffectation, replace by `let“
Should I use var?
Even if var still works, it is discouraged due to potential confusion in many case. Replace var by let, or better by const if variable is not reassigned.