JavaScript Variables
JavaScript variables are named containers for storing data. You declare a variable with let, const or the older var keyword, and then refer to the value by its name.
Declaring Variables with let and const
Use const for values that will not be reassigned, and let for values that will change. Start with const by default; switch to let only when you need to reassign.
const name = "Ayesha";
let score = 10;
score = score + 5; // allowed: let can be reassigned
console.log(name, score);
// name = "Bilal"; // TypeError: Assignment to constant variable.Ayesha 15
const Does Not Mean Immutable
const stops reassignment of the variable, but if the value is an object or array, its contents can still change.
const cart = ["apple"];
cart.push("bread"); // fine: we change the array, not the variable
console.log(cart);
const user = { age: 30 };
user.age = 31;
console.log(user.age);[ "apple", "bread" ] 31
let vs var
var is the original way to declare variables. It is function-scoped and hoisted with the value undefined, which causes subtle bugs. let and const are block-scoped: they only exist inside the nearest { }. In modern code, avoid var.
if (true) {
var a = "var leaks out";
let b = "let stays inside";
}
console.log(a);
console.log(typeof b); // b is not defined herevar leaks out undefined
Variable Naming Rules
- Names can contain letters, digits, underscore (_) and dollar sign ($)
- Names cannot start with a digit
- Names are case sensitive (age and Age differ)
- Reserved words like let, class or return cannot be used
- Use descriptive camelCase names: userCount, isLoggedIn
- Constants known before runtime are often written in UPPER_SNAKE_CASE: MAX_SIZE
Declaring Several Variables
You can declare multiple variables in one statement, separated by commas, or unpack values with destructuring (covered later).
let x = 1, y = 2, z = 3;
console.log(x + y + z);
const [first, second] = ["red", "green"];
console.log(first, second);
let empty;
console.log(empty); // declared but not assigned6 red green undefined
Frequently asked questions
Should I use let or const in JavaScript?
Use const by default and let only when the variable must be reassigned. This makes your intent clear and prevents accidental changes.
Why should I not use var?
var ignores block scope and is hoisted, so a variable can be used before its declaration line and can leak out of if blocks and loops. let and const fix both problems.
What happens if I use a variable before declaring it with let?
You get a ReferenceError. let and const variables are in a "temporal dead zone" until their declaration line runs.