By the end of this lesson, learners will:
var, let, and constA variable is a container that holds a value so you can use it or change it later in your program.
Think of it like a labeled box:
You write the label (userName), and you put something inside (like "Alice").
There are three keywords to declare a variable in modern JavaScript:
| Keyword | Can Reassign? | Scope | Description |
|---|---|---|---|
var | ✅ Yes | Function | Old way (not recommended) |
let | ✅ Yes | Block | Recommended for variables that change |
const | ❌ No | Block | Recommended for variables that don’t change |
let (Modern and Recommended)let age = 25;
console.log(age); // 25
age = 26;
console.log(age); // 26
let variable.{ } block it’s defined in.const (For Fixed Values)const birthYear = 2000;
console.log(birthYear); // 2000
// birthYear = 2001; ❌ This would cause an error!
const variables cannot be reassigned.var (Old and Avoided)var name = "Alice";
console.log(name); // Alice
var name = "Bob";
console.log(name); // Bob
var variables — this can lead to bugs.✅ Best practice: Avoid var in modern JavaScript.
let city = "Berlin"; // string
const pi = 3.14159; // number
let isStudent = true; // boolean
let temperature; // undefined
console.log(message); // ❌ ReferenceError
let message = "Hello!";
JavaScript reads top-down, so declare your variables before you try to use them.
_, or dollar sign $_, and $let, return, function, etc.)✅ Valid:
let userName;
let $price;
let _totalAmount;
❌ Invalid:
let 1stPlace; // Cannot start with number
let let = 10; // Cannot use reserved keyword
{} — used by let and constvar{
let x = 10;
console.log(x); // 10
}
console.log(x); // ❌ Error: x is not defined
| Practice | Reason |
|---|---|
Use let for changing values | It’s flexible and safe |
Use const for fixed values | Prevents accidental changes |
Avoid var | Can lead to bugs due to scoping issues |
| Name variables clearly | Improves readability and maintainability |
| Use camelCase | e.g., userAge, totalPrice |
Try this in your browser console:
let user = "Alice";
const year = 2025;
console.log(user); // Alice
user = "Bob";
console.log(user); // Bob
// year = 2030; ❌ Error: Assignment to constant variable
| Feature | var | let | const |
|---|---|---|---|
| Reassignable? | ✅ Yes | ✅ Yes | ❌ No |
| Redeclarable? | ✅ Yes | ❌ No | ❌ No |
| Scope | Function | Block | Block |
| Use Case | Legacy code only | Changing values | Fixed values |