DEV Community

Sudhakar V
Sudhakar V

Posted on

JavaScript Variable Declarations -let, const & var

🧠 let, const, and var**


🔸 var – The Old Way (ES5)

  • Introduced in early versions of JavaScript.
  • Function-scoped
  • Can be redeclared and updated
  • Hoisted (moved to the top of the scope)

✅ Example:

var x = 10;
var x = 20; // No error (redeclared)
console.log(x); // 20
Enter fullscreen mode Exit fullscreen mode

⚠️ Problem:

if (true) {
  var test = "hello";
}
console.log(test); // hello (leaks outside the block)
Enter fullscreen mode Exit fullscreen mode

🔹 let – Modern Way (ES6)

  • Introduced in ES6 (2015)
  • Block-scoped
  • Can be updated but not redeclared in the same scope
  • Not hoisted (in a usable way)

✅ Example:

let a = 5;
a = 10; // OK
// let a = 15; ❌ Error: Identifier 'a' has already been declared
Enter fullscreen mode Exit fullscreen mode
if (true) {
  let msg = "inside";
  console.log(msg); // inside
}
// console.log(msg); ❌ Error: msg is not defined
Enter fullscreen mode Exit fullscreen mode

🔒 const – For Constants (ES6)

  • Also block-scoped
  • Cannot be updated or redeclared
  • Must be initialized at the time of declaration

✅ Example:

const pi = 3.14;
// pi = 3.14159; ❌ Error: Assignment to constant variable
Enter fullscreen mode Exit fullscreen mode

⚠️ Objects with const:

You can change object properties, but not reassign the object.

const person = { name: "Sudhakar" };
person.name = "SK";  // ✅ OK
// person = {}; ❌ Error
Enter fullscreen mode Exit fullscreen mode

📊 Comparison Table

Feature var let const
Scope Function Block Block
Hoisting Yes (initialized as undefined) Yes (but not initialized) Yes (but not initialized)
Re-declaration ✅ Allowed ❌ Not allowed ❌ Not allowed
Re-assignment ✅ Allowed ✅ Allowed ❌ Not allowed
Initialization Optional Optional ✅ Required
Use Case Legacy code Variables that change Fixed values / constants

✅ Best Practices

  • Use const by default
  • Use let when the value needs to change
  • Avoid var (use only in legacy projects)

Top comments (0)