Let & const | Dataplexa

let & const

One of the most important improvements introduced in ES6 is the way JavaScript handles variables.

The keywords let and const were created to replace many problems caused by var.


Why var Was a Problem

Before ES6, JavaScript used var for declaring variables.

This caused issues such as:

  • Variables being accessible outside their intended scope
  • Accidental overwriting of values
  • Hard-to-debug behavior in large codebases

let and const were introduced to fix these issues.


What Is let?

let allows you to declare variables whose values can be changed later.


let count = 1;
count = 2;
  

Variables declared with let are block-scoped.


Block Scope Explained

Block scope means a variable exists only inside the block where it is declared.


if (true) {
  let message = "Hello";
}

console.log(message); // Error
  

This prevents unintended access to variables.


What Is const?

const is used to declare variables whose values should not be reassigned.


const siteName = "Dataplexa";
  

Once assigned, the variable cannot be changed.


Important Note About const

const prevents reassignment, not modification of objects or arrays.


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

The reference stays the same, but the content can change.


When to Use let vs const

  • Use const by default
  • Use let when reassignment is required
  • Avoid var in modern JavaScript

Real-World Example

Tracking a counter value:


let clicks = 0;

button.addEventListener("click", function () {
  clicks++;
});
  

Here, let is appropriate because the value changes.


Common Beginner Mistakes

  • Using let everywhere instead of const
  • Trying to reassign a const variable
  • Mixing var with modern syntax

Choosing the right keyword improves code safety.


Thumb Rules

  • Prefer const by default
  • Use let when values change
  • Avoid var in modern code
  • Think in terms of scope

What Comes Next?

Now that variables are clearer, the next step is writing cleaner functions.

In the next lesson, we will learn about arrow functions.