Problem Statement
What is the main difference between var and let?
Explanation
The key difference is scope.
Var has function scope. It is accessible anywhere within the entire function, even outside blocks like if statements or loops. This causes variables to leak out of blocks.
Let has block scope. It only exists within the curly braces where it is defined. This is safer and prevents variable leaking.
Modern JavaScript always uses let and const over var.
Code Solution
SolutionRead Only
// var - function scoped (leaks out of blocks)
function testVar() {
if (true) {
var x = 10; // Accessible everywhere in function
}
console.log(x); // 10 - Still accessible! (BAD)
}
// let - block scoped (stays inside block)
function testLet() {
if (true) {
let y = 10; // Only accessible in this block
}
console.log(y); // Error! y is not defined (GOOD)
}
// Real example - loop with var
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 3, 3, 3 (all reference same i)
// Same loop with let
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 0, 1, 2 (each has own i)