Variables declared with **let** are block-scoped and can be reassigned. **const** creates a block-scoped binding that cannot be reassigned (but objects/arrays can be mutated). **var** is function-scoped and hoisted — avoid it in modern code.
1Understanding Variables
Variables declared with let are block-scoped and can be reassigned. const creates a block-scoped binding that cannot be reassigned (but objects/arrays can be mutated). var is function-scoped and hoisted — avoid it in modern code.
Prefer const by default; use let when reassignment is needed; avoid var entirely.
// let vs const
let count = 0;
count = 1; // OK
const MAX = 100;
// MAX = 200; // TypeError!
const user = { name: 'Alice' };
user.name = 'Bob'; // OK - mutating the object2Practical Example
Here is a real-world application of Variables showing how it is used in production JavaScript code.
// Block scope
{
let blockVar = 'inside';
console.log(blockVar); // 'inside'
}
// console.log(blockVar); // ReferenceError
var funcVar = 'I leak outside blocks';
if (true) { var funcVar = 'changed!'; }
console.log(funcVar); // 'changed!'3Best Practices
Follow these guidelines when working with Variables:
1. Use const for values that don't change
2. Use let for loop counters and reassigned values
3. Avoid var to prevent hoisting surprises
Tip: Prefer const by default; use let when reassignment is needed; avoid var entirely.
// let vs const
let count = 0;
count = 1; // OK
const MAX = 100;
// MAX = 200; // TypeError!
const user = { name: 'Alice' };
user.name = 'Bob'; // OK - mutating the object