Programs & Examples
Variables: var, let and const · Study material
Bank statement with const and let
The opening balance and the transaction list never change (const); the running balance does (let). Destructuring in the loop head reads each transaction's fields.
// const for values that never change, let for the running balance
const OPENING_BALANCE = 5000;
const transactions = [
{ type: "deposit", amount: 2500 },
{ type: "withdraw", amount: 1200 },
{ type: "withdraw", amount: 7000 }, // more than the balance: rejected
{ type: "deposit", amount: 800 },
];
let balance = OPENING_BALANCE;
for (const { type, amount } of transactions) {
if (type === "withdraw" && amount > balance) {
console.log(`Rejected withdrawal of ${amount} (balance ${balance})`);
continue;
}
balance += type === "deposit" ? amount : -amount;
console.log(`${type.padEnd(8)} ${String(amount).padStart(5)} → balance ${balance}`);
}
console.log("Closing balance:", balance);
deposit 2500 → balance 7500 withdraw 1200 → balance 6300 Rejected withdrawal of 7000 (balance 6300) deposit 800 → balance 7100 Closing balance: 7100
Each iteration's own variable
The loop example on the Introduction tab shows the classic interview output: var prints 3, 3, 3, while let prints 0, 1, 2.