JavaScript Variables Explained: var, let, and const

Variables are fundamental in JavaScript, allowing you to store, update, and access values. Over time, JavaScript has introduced different ways to declare variables: var, let, and const. Understanding their differences is crucial for writing clean, predictable, and bug-free code.


1. var: The Classic Way

var is the original way to declare variables in JavaScript.

var name = 'John';
console.log(name); // John

Key characteristics of var:

  • Function-scoped: Available throughout the function it is declared in.
  • Hoisting: Variables are “hoisted” to the top of their scope but initialized as undefined.
console.log(age); // undefined
var age = 25;
  • Can be redeclared and updated:
var age = 30;
age = 35;
console.log(age); // 35

Caution: var can lead to unexpected behavior due to hoisting and lack of block scope.


2. let: The Modern Approach

let was introduced in ES6 to provide block-level scope, making it safer than var.

let city = 'New York';
console.log(city); // New York

Key characteristics of let:

  • Block-scoped: Only accessible within the {} block where it’s declared.
  • Cannot be redeclared in the same scope.
  • Can be updated:
let score = 10;
score = 15;
console.log(score); // 15
  • Hoisting exists, but the variable is in a temporal dead zone until initialized:
console.log(score); // ReferenceError
let score = 10;

3. const: Constant Variables

const is used for variables that should not be reassigned.

const pi = 3.14159;
console.log(pi); // 3.14159

Key characteristics of const:

  • Block-scoped like let.
  • Cannot be redeclared or reassigned.
  • Must be initialized at declaration.
  • For objects and arrays, the reference is constant, but the contents can change:
const user = { name: 'Alice' };
user.name = 'Bob'; // Allowed
console.log(user.name); // Bob

const numbers = [1, 2, 3];
numbers.push(4); // Allowed
console.log(numbers); // [1, 2, 3, 4]

4. Comparing var, let, and const

Featurevarletconst
ScopeFunctionBlockBlock
RedeclarableYesNoNo
ReassignableYesYesNo
HoistingYesYes (TDZ)Yes (TDZ)

Summary: Use let for variables that change and const for values that remain constant. Avoid var unless maintaining legacy code.


5. Best Practices

  • Prefer const by default for clarity.
  • Use let when the variable’s value will change.
  • Avoid var to prevent scope-related bugs.
  • Use descriptive variable names for readability.

6. Wrapping Up

Understanding var, let, and const is essential for writing modern, maintainable JavaScript code. Proper use of these keywords prevents common bugs, improves code readability, and aligns with ES6 standards.


Next Step: Explore variable hoisting and scope chains to deepen your understanding of JavaScript execution context.