JS Variables
On this page
Declaring Variables
In JavaScript, variables are declared using let, const, or (legacy) var.
let age = 25; const siteName = "W4"; var oldStyle = "legacy";
let
let is used for variables that can change. It is block-scoped, meaning it only exists inside the block where it is defined.
let count = 0;
count = count + 1;
if (true) {
let message = "Inside block";
console.log(message);
}
const
const is used for variables that should not be reassigned. It must be initialized when declared.
const pi = 3.14159; // pi = 3; // Error
Note: const prevents reassignment, but objects and arrays declared with const can still be modified internally.
const user = { name: "John" };
user.name = "Jane"; // Allowed
var (Legacy)
var is function-scoped and can lead to unexpected behavior. It is recommended to use let or const in modern JavaScript.
var x = 10;
if (true) {
var x = 20;
}
console.log(x); // 20
Block Scope Example
Variables declared with let and const are limited to the block in which they are defined.
if (true) {
let value = 100;
}
// console.log(value); // Error
Best Practice
Use const by default. Use let only when reassignment is required. Avoid var in modern code.