In JavaScript, a variable is like a labeled box where you can store information (a value). To use these boxes, you must first "declare" them. Let's see how to do this with modern JavaScript tools.
let
: The Reassignable Variable
let
is the most common way to declare a variable whose value is likely to change.
You can do this in two steps: first the declaration, then the assignment.
// 1. Declaration of the variable "message"
let message;
// 2. Assignment of the value 'Hello World'
message = 'Hello World';
console.log(message); // Displays "Hello World"
To be more concise, you can declare and assign the value in a single line:
let message2 = 'Hello World';
console.log(message2); // Displays "Hello World"
const
: The Immutable Constant
When you know that a value should never change, you use const
. This is a good practice to make your code safer and more readable.
const monAnniversaire = '15.04.1990';
console.log(monAnniversaire); // Displays "15.04.1990"
A constant has strict rules:
- It must be initialized with a value during its declaration.
- You cannot change its value after its declaration.
// Trying to change the value will throw an error!
// monAnniversaire = '01.01.2000'; // TypeError: Assignment to constant variable.
Roughly, it's like let
, but without the possibility of modification!
The Old Method: var
In older scripts, you will often see the keyword var
.
var messageAncien = 'Hello World';
var
works differently from let
, especially in how the variable "exists" in your code (this is called the "scope"). By modern convention, we always prefer let
and const
. We will see the differences in more detail later.
Note on Readability
It is possible to declare multiple variables on a single line, but this is not recommended because it makes the code harder to read.
// Possible, but to be avoided
let prenom = 'Jean', age = 41, estMajeur = true;
Mastering let
and const
is the first essential step to writing modern and reliable JavaScript.