SmartCodingTips

JavaScript Variables: var, let, and const

In JavaScript, variables are used to store data values like numbers, strings, arrays, and objects. You can declare variables using var, let, or const. Let’s understand the differences and when to use each.

πŸͺ™ 1. var – The Old Way

var was the original way to declare variables in JavaScript. It has function-level scope and can be redeclared.

var name = "Alice";
console.log(name); // Alice

var name = "Bob";  // Redeclared
console.log(name); // Bob
  • Function-scoped
  • Can be redeclared and reassigned
  • Hoisted (but undefined at the top)

πŸ”’ 2. let – The Modern Standard

let is block-scoped and prevents variable redeclaration.

let age = 25;
age = 26;      // βœ… Reassignment allowed

let age = 30;  // ❌ Error: Cannot redeclare
  • Block-scoped (works inside {})
  • Can be reassigned, but not redeclared in the same scope
  • Also hoisted, but not initialized

🧊 3. const – For Constants

const is also block-scoped and must be initialized when declared. The value cannot be reassigned.

const PI = 3.1416;
PI = 3.14; // ❌ Error: Assignment to constant variable

const user = { name: "Alice" };
user.name = "Bob"; // βœ… Allowed (object itself not reassigned)
  • Block-scoped
  • Must be initialized
  • Can't be reassigned, but object properties can change

βš–οΈ Summary: When to Use What?

Feature var let const
Scope Function Block Block
Hoisting Yes (undefined) Yes (TDZ) Yes (TDZ)
Reassignable Yes Yes No
Redeclarable Yes No No
Best Practice: Use let for variables that will change, and const for those that shouldn’t. Avoid var in modern JavaScript.