JavaScript Variables
In programming, a variable is simply a named container for storing a piece of information, or data. Think of it like a label you stick onto a box; you can easily find the box later by reading the label, and you can change what’s inside the box whenever you need to.
Variables are the most fundamental concept in coding because they allow you to manage data, perform calculations, and refer to information later in your program.
Declaring Variables: The Three Keywords
1. const (The Constant Container)
The const keyword is the most important one and should be your default choice for declaring variables.
- Use: Use it for anything that should never change, like a fixed tax rate, a person’s name, or a birthday.
- Rule: The value inside a
constcontainer cannot be changed or reassigned after it is first created. It’s constant.
const userName = "Rodney"; //"String"
const PI = 3.14159; //Number
// If you try to reassign a const variable, JavaScript will throw an error:
//userName = "Alex"; //Uncaught TypeError: Assignment to constant variable.JavaScript2. let (The Flexible Container)
The let keyword is used for variables whose value you expect to change at some point in your program.
- Rule: The value inside a
letcontainer can be changed or reassigned later. - Use: Use it for things that change, like a user’s current score, a count in a loop, or a shopping cart total.
let score = 0; // Initialize score to 0
// Later in the program, you can change the value:
score = 100; // score is now 100
let greeting = "Hello";
greeting = "Goodbye"; // greeting is now "Goodbye"JavaScript3. var (The Older Container)
The var keyword is the original way to declare variables in JavaScript.
- Rule: Like
let, the value can be changed. - Recommendation: Avoid using
varin new code. It has confusing rules related to a concept called scope (which you’ll learn about later) that can lead to bugs. Modern JavaScript development almost exclusively usesconstandlet.
Best Practice: const First
When starting a new variable, always try to use const first. If you later find you absolutely need to change the variable’s value, switch it to let. By using const as much as possible, you make your code safer and easier to predict.




