Understanding let, const, and var in JavaScript 🚀

Andy WaithakaAndy Waithaka
4 min read

Introduction

If you’ve been learning JavaScript, you’ve probably come across it. var, let, and const. These keywords are used to declare variables, but they behave differently. Understanding how and when to use them is crucial for writing clean and bug-free code.

In this post, we’ll break down the differences between var, let, and const, explore their scoping rules, and look at best practices for using them in your JavaScript projects.


1. var – The Old Way of Declaring Variables

Before ES6 (ECMAScript 2015), var it was the only way to declare variables in JavaScript. However, it has some issues that can lead to unexpected behavior.

Example of var in Action:

javascriptCopyEditvar name = "Anderson";
console.log(name); // Output: Anderson

var name = "Mundia";
console.log(name); // Output: Mundia

👉 var Allows redeclaration, meaning you can declare the exact variable multiple times, which can cause bugs in large codebases.

Function Scope vs. Block Scope

Variables declared with var are function-scoped, meaning they are accessible throughout the function in which they are declared.

javascriptCopyEditfunction example() {
  if (true) {
    var x = 10;
  }
  console.log(x); // Output: 10 (Accessible outside the block)
}
example();

Even though x is declared inside the if block, it is still accessible outside because var does not have a block scope.


2. let – The Modern and Safer Alternative

let was introduced in ES6 and is now the preferred way to declare variables when their values may change.

Key Features of let:

Block-scoped – Only accessible within the block {} where it is declared.
Cannot be redeclared – Prevents accidental overwriting of variables.

Example of let in Action:

javascriptCopyEditlet age = 25;
console.log(age); // Output: 25

age = 30; // Allowed (Reassignment)
console.log(age); // Output: 30

// let age = 35; ❌ Error: Cannot redeclare variable

Block Scope Example:

javascriptCopyEditif (true) {
  let y = 20;
  console.log(y); // Output: 20
}
console.log(y); // ❌ Error: y is not defined (block-scoped)

Unlike var, y is not accessible outside the if block.


3. const – For Constants (Immutable Variables)

If you never want a variable’s value to change, use const.

Key Features of const:

Must be initialized – You must assign a value when declaring it.
Cannot be reassigned – The value cannot be changed once assigned.
Block-scoped – Similar to let, it respects block scope.

Example of const in Action:

javascriptCopyEditconst PI = 3.14159;
console.log(PI); // Output: 3.14159

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

Mutable Objects and Arrays

While const prevents reassignment, it does not make objects and arrays immutable.

javascriptCopyEditconst person = { name: "Anderson", age: 25 };
person.age = 30; // Allowed
console.log(person.age); // Output: 30

// person = { name: "John" }; ❌ Error: Cannot reassign a constant object

You can modify the properties of a const object, but you cannot reassign the entire object.


4. Summary Table: var Vs. let Vs. const

Featurevarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
Redeclaration✅ Allowed❌ Not Allowed❌ Not Allowed
Reassignment✅ Allowed✅ Allowed❌ Not Allowed
Hoisting✅ Hoisted (but undefined)✅ Hoisted (not initialized)✅ Hoisted (not initialized)

5. Best Practices for Declaring Variables

🔹 Use const by default – If you don’t need to reassign a variable, always use const.
🔹 Use let when reassignment is necessary – For example, in loops or state changes.
🔹 Avoid var ultimately – It can lead to unexpected bugs due to its function scoping.


6. Real-World Example: Using let and const Together

Let’s see how let and const can work together in a real-world scenario.

javascriptCopyEditconst user = { name: "Anderson", role: "Developer" };

if (user.role === "Developer") {
  let accessLevel = "Admin";
  console.log(`${user.name} has ${accessLevel} access.`); 
}

console.log(user.name); // ✅ Works
// console.log(accessLevel); ❌ Error (accessLevel is block-scoped)

Here, const ensures that user remains the same object while let ensures that accessLevel is only accessible inside the if block.


Conclusion

Understanding var, let, and const is fundamental to writing clean JavaScript code. Always remember:

✔️ Use const values that shouldn’t change.
✔️ Use let when you need a variable that might change.
Avoid var to prevent scoping issues and accidental redeclaration.

I hope this post clarifies the differences! Have any questions or thoughts? Please drop a comment below or connect with me on GitHub: Mundia1.

🚀 Happy Coding! 🚀

0
Subscribe to my newsletter

Read articles from Andy Waithaka directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Andy Waithaka
Andy Waithaka