JavaScript Variables: Understanding var, let, and const

4/13/2025

#JavaScript Variables: Understing var, let, and const

Go Back

JavaScript Variables: Understanding var, let, and const

Variables are the foundation of any programming language. In JavaScript, we use variables to store data that can be used and manipulated throughout our code. JavaScript provides three main ways to declare variables: var, let, and const. While they may seem similar at first glance, they have distinct behaviors and use cases.

In this article, we'll break down the differences and guide you on when to use each one.


#JavaScript Variables: Understing var, let, and const

1. var – The Traditional Way

var is the original way to declare variables in JavaScript and has been around since the language was created.

var name = "John";

🔹 Characteristics:

  • Function-scoped: Accessible within the function where it's declared.

  • Can be re-declared and updated.

  • Hoisted to the top of the scope but initialized as undefined.

⚠️ Common Issues:

console.log(a); // undefined
var a = 5;

This happens due to hoisting, where the declaration is moved to the top, but not the value assignment.


2. let – The Modern and Safe Way

Introduced in ES6 (ECMAScript 2015), let is block-scoped and designed to fix many of the problems with var.

let age = 30;
age = 31; // allowed

🔹 Characteristics:

  • Block-scoped: Only accessible within the block ({}) it's declared.

  • Cannot be re-declared in the same scope.

  • Can be updated.

  • Not hoisted in the same way as var (temporal dead zone).

✅ Example:

if (true) {
  let message = "Hello";
  console.log(message); // Hello
}
console.log(message); // ReferenceError

3. const – For Constants

Also introduced in ES6, const is used to declare variables whose values should not change.

const pi = 3.14;

🔹 Characteristics:

  • Block-scoped like let.

  • Must be initialized at the time of declaration.

  • Cannot be updated or re-declared.

  • Does not make objects immutable (only the binding is constant).

✅ Example:

const person = { name: "Alice" };
person.name = "Bob"; // Allowed
person = { name: "Charlie" }; // Error

4. Comparison Table

Feature var let const
Scope Function Block Block
Re-declaration Allowed Not allowed Not allowed
Reassignment Allowed Allowed Not allowed
Hoisting Yes (initialized as undefined) Yes (TDZ) Yes (TDZ)
Use Case Legacy code General use Constants (fixed values)

5. Best Practices

  • Use const by default.

  • Use let when you know the value will change.

  • Avoid using var unless maintaining legacy code.


Final Thoughts

Understanding the differences between var, let, and const is key to writing clean, bug-free JavaScript code. Stick with let and const in modern development to take advantage of block scoping and avoid common pitfalls. Happy coding!

Table of content