JavaScript Variables
Variables are containers for storing data values. JavaScript has three ways to declare a variable: var, let, and const.
Which One to Use?
The general rule: always declare variables with const. Use let only if the value will change. Avoid var in modern code.
| Keyword | Scope | Reassign | Redeclare | Hoisted |
|---|---|---|---|---|
| var | Function | ✓ | ✓ | ✓ (as undefined) |
| let | Block | ✓ | ✗ | ✗ (TDZ) |
| const | Block | ✗ | ✗ | ✗ (TDZ) |
Declaring Variables
All three keywords are shown below. Notice that const requires an initial value.
Example
var name = "Alice"; // function-scoped, avoid in modern code
let age = 30; // block-scoped, value can change
const PI = 3.14159; // block-scoped, cannot be reassigned
console.log(name);
console.log(age);
console.log(PI);One Statement, Many Variables
Example
let person = "Alice", car = "Volvo", price = 200;
console.log(person, car, price);Declaring Without Assigning
Undefined Variables
let x;
console.log(x); // undefined
x = 42;
console.log(x); // 42📝 Note: It is good practice to always declare variables at the top of their scope.
Exercise:
Which keyword should you use to declare a variable that will NOT change?