Different Between Let vs Var in JavaScript

Difference Between let and var in JavaScript

Both let and var are used to declare variables in JavaScript, but they have key differences in terms of scope, re-declaration, and hoisting.

1. Scope

var is function-scoped, whereas let is block-scoped.


// Using var
function exampleVar() {
    if (true) {
        var a = 10;
    }
    console.log(a); // Works because var is function-scoped
}
exampleVar();

// Using let
function exampleLet() {
    if (true) {
        let b = 20;
    }
    console.log(b); // Error: b is not defined (because let is block-scoped)
}
exampleLet();

2. Re-declaration

var allows re-declaration within the same scope, but let does not.


// var allows re-declaration
var x = 5;
var x = 10;
console.log(x); // 10

// let does not allow re-declaration
let y = 15;
let y = 25; // Error: Identifier 'y' has already been declared

3. Hoisting

Both var and let are hoisted, but var is initialized with undefined, whereas let remains uninitialized.


// var is hoisted and initialized with undefined
console.log(z); // undefined
var z = 30;

// let is hoisted but not initialized
console.log(w); // Error: Cannot access 'w' before initialization
let w = 40;

Conclusion

It is recommended to use let instead of var in modern JavaScript, as let provides better scoping, avoids unintended re-declarations, and reduces bugs caused by hoisting.