16. What is the difference between let and var?

S
Soumya Jana
Mon Feb 24 2025

The difference between let and var in JavaScript mainly lies in scope, hoisting, and re-declaration.

Key Differences:

  1. Scope:

    • var is function-scoped (accessible throughout the function).
    • let is block-scoped (accessible only within {} where it is defined).
  2. Hoisting:

    • var is hoisted and initialized as undefined.
    • let is hoisted but not initialized (using it before declaration gives a ReferenceError).
  3. Re-declaration:

    • var can be re-declared within the same scope.
    • let cannot be re-declared within the same scope.

Example:

javascript
function test() { if (true) { var x = 10; // Function-scoped let y = 20; // Block-scoped } console.log(x); // ✅ Works (var is accessible) console.log(y); // ❌ Error (let is block-scoped) } test();

Hoisting Example:

javascript
console.log(a); // ✅ Output: undefined (var is hoisted) var a = 5; console.log(b); // ❌ ReferenceError (let is not initialized) let b = 10;

Conclusion:

  • Use let to avoid unexpected behavior due to var's function-scoping and hoisting.
  • Prefer let over var in modern JavaScript. 🚀

Related Posts:

View All Related Posts
Sign In To Write A Comment
Copyright © 2025 codewithjana.com