Variables (var, let, const)

In JavaScript, variables store data values. There are three main ways to declare variables: var, let, and const. Understanding their differences is crucial for writing clean and bug-free code.

Illustration of variables_var_let_const
Illustration of variables_var_let_const

💡 Variable Declaration Overview

  • var – function-scoped, can be redeclared and updated.
  • let – block-scoped, can be updated but not redeclared in the same scope.
  • const – block-scoped, cannot be updated or redeclared; must be initialized.
Comparison of var, let, and const
Featurevarletconst
ScopeFunctionBlockBlock
HoistingYes (initialized with undefined)Yes (not initialized)Yes (not initialized)
Redeclaration in same scopeAllowedNot allowedNot allowed
ReassignmentAllowedAllowedNot allowed
Must be initialized?NoNoYes

⚠️ Avoid Using var in Modern Code

Because var has function scope and hoisting behavior that can cause unexpected bugs, it's best to prefer let and const in modern JavaScript.

📌 Deep Dive: Declaring Variables with let and const

JAVASCRIPT
let age = 30;
age = 31; // Allowed

const name = "Alice";
// name = "Bob"; // Error: Assignment to constant variable

if (true) {
  let blockScoped = "inside block";
  const blockConst = 100;
}
// console.log(blockScoped); // ReferenceError
    
Output
No output, but reassigning name throws error, and blockScoped is not accessible outside the block.

💡 Best Practices

  • Use const by default for all variables that won't change.
  • Use let only when you need to reassign the variable.
  • Avoid var to prevent scope and hoisting issues.

📌 Deep Dive: var Hoisting and Scope

JAVASCRIPT
console.log(x); // undefined due to hoisting
var x = 5;

if (true) {
  var y = 10;
}
console.log(y); // 10 - var is function-scoped, not block-scoped
    
Output
undefined
10

⚠️ Redeclaring Variables

Redeclaring a variable with var in the same scope is allowed and can cause confusion. let and const prevent redeclaration in the same scope, helping avoid bugs.

💡 Summary

  • var: function-scoped, hoisted, can be redeclared and reassigned.
  • let: block-scoped, hoisted but uninitialized, can be reassigned but not redeclared.
  • const: block-scoped, hoisted but uninitialized, cannot be reassigned or redeclared; must be initialized.