Skip to content
blog
2 min read

Declare Variable

Learn to declare variables in JavaScript to make code meaningful and manageable. Use const for fixed values and let for mutable ones, avoiding var.

A variable is a named container for a value. Declaring one tells JavaScript to reserve a spot in memory and give it a label.

Three Ways to Declare

const name = "Reza"; // constant — can't be reassigned
let age = 28; // can be reassigned
var city = "Jakarta"; // old way — avoid

const

Use const by default. It signals that this value won’t change:

const PI = 3.14159;
const MAX_RETRIES = 3;
const user = { name: "Reza" };

const prevents reassignment, not mutation. You can still modify the contents of an object or array:

const user = { name: "Reza" };
user.name = "Ali"; // fine — modifying the object, not the binding
user = {}; // TypeError — can't reassign

let

Use let when the value needs to change:

let count = 0;
count = count + 1; // fine
count++; // also fine

Common for loop counters and values that accumulate:

let total = 0;
for (const price of prices) {
total += price;
}

Why Not var

var has function scope instead of block scope, which causes surprising behavior:

if (true) {
var x = 10;
}
console.log(x); // 10 — leaked out of the if block
if (true) {
let y = 10;
}
console.log(y); // ReferenceError — correctly scoped

var is also hoisted in a way that can lead to bugs. There’s no reason to use it in new code.

Naming Variables

  • Use camelCase: firstName, totalPrice, isActive
  • Be descriptive: userAge not a, itemCount not n
  • Use CONSTANT_CASE for top-level constants: MAX_SIZE, API_URL