No, var and let work differently inside a function. The main difference is scope:
function example() {
if (true) {
var a = 1; // visible throughout function
let b = 2; // visible only in if block
}
console.log(a); // 1 (works)
console.log(b); // ReferenceError (error!)
}[var] and [let] inside a function are like two friends with different rules: [var] shares everything with everyone in the room (function), while [let] shows toys only to those in a specific box (block)! 📦
The main difference between [var] and [let] is scope:
function scopeExample() {
if (true) {
var varVariable = 'var inside if';
let letVariable = 'let inside if';
}
console.log(varVariable); // 'var inside if' (accessible)
console.log(letVariable); // Error! (not accessible)
}function redeclareExample() {
var a = 1;
var a = 2; // Allowed — var allows redeclaration
console.log(a); // 2
let b = 1;
// let b = 2; // Error! (can't redeclare let)
}function varHoisting() {
console.log(a); // undefined (no error!)
var a = 5;
console.log(a); // 5
}
// Actually JavaScript does:
// function varHoisting() {
// var a; // hoists declaration
// console.log(a); // undefined
// a = 5;
// console.log(a); // 5
// }function letHoisting() {
// console.log(b); // ReferenceError! (in temporal dead zone)
let b = 5;
console.log(b); // 5
}function loopExample() {
// With var — one variable for all iterations
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var:', i), 100); // 3, 3, 3
}
// With let — own variable for each iteration
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log('let:', j), 100); // 0, 1, 2
}
}function conditionalExample(condition) {
if (condition) {
var a = 'var';
let b = 'let';
}
console.log(a); // undefined or 'var' (accessible)
// console.log(b); // ReferenceError! (not accessible)
}function commonMistake() {
if (true) {
var result = 'result';
}
// ❌ Expecting error, but var is accessible
console.log(result); // 'result' (no error!)
}function anotherMistake() {
// ❌ Error with let
// console.log(x); // ReferenceError!
let x = 10;
// ✅ With var works (but better not to do this)
console.log(y); // undefined
var y = 20;
}Understanding the difference helps write more predictable code and avoid scope-related errors! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪