0
0
Javascriptprogramming~3 mins

Why Variable declaration using const in Javascript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could stop bugs before they happen by locking your values?

The Scenario

Imagine you are writing a program where you need to store a value that should never change, like the number of days in a week. You write the value once and then accidentally change it later in your code.

The Problem

Without a way to lock a value, you might accidentally overwrite important data. This can cause bugs that are hard to find because the program behaves unpredictably when values change unexpectedly.

The Solution

Using const lets you declare variables that cannot be reassigned. This means once you set a value, the program will prevent you from changing it, keeping your data safe and your code more reliable.

Before vs After
Before
let daysInWeek = 7;
daysInWeek = 8; // Oops, changed by mistake!
After
const daysInWeek = 7;
daysInWeek = 8; // Error: Assignment to constant variable.
What It Enables

It enables you to write safer code by protecting important values from accidental changes.

Real Life Example

Think of const like labeling a jar as 'Do Not Open' so no one accidentally changes what's inside, like setting the speed limit on a road that should never change.

Key Takeaways

const prevents variables from being reassigned.

It helps avoid bugs caused by accidental changes.

Using const makes your code clearer and safer.