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)