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.
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.
const name = "Reza"; // constant — can't be reassignedlet age = 28; // can be reassignedvar city = "Jakarta"; // old way — avoidUse 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 bindinguser = {}; // TypeError — can't reassignUse let when the value needs to change:
let count = 0;count = count + 1; // finecount++; // also fineCommon for loop counters and values that accumulate:
let total = 0;for (const price of prices) { total += price;}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 scopedvar is also hoisted in a way that can lead to bugs. There’s no reason to use it in new code.
firstName, totalPrice, isActiveuserAge not a, itemCount not nMAX_SIZE, API_URL