🧠 Using const with Arrays in JavaScript

🧠 Using const with Arrays in JavaScript

The “Immutable Variables” Myth, the Truth, and a Few Tiny Betrayals

There’s a classic moment everyone experiences while learning JavaScript:

“Teacher, I used const, but this array is still changing…”
“Is JavaScript lying to me?”

No.
JavaScript doesn’t lie—
it just subtly sets a trap 😄

In this article, we’ll cover:

  • What const actually locks
  • Why arrays can still change
  • What you can and cannot do
  • Why professionals constantly use const
  • Practical tips you’ll actually use in real projects

All explained with lots of examples and plenty of analogies.


📦 1. What Did const Mean Again? (A Short but Vital Reminder)

Let’s start from the basics.

const age = 25;
age = 30;

If you run this, JavaScript says:

TypeError: Assignment to constant variable

Which means:

  • const → reassignment is forbidden
  • Value = primitive (number, string, boolean)

So far, everything makes sense.


🤯 2. Same const, Same JavaScript… But the Array Changes?!

Now let the array enter the stage:

const numbers = [1, 2, 3];

numbers.push(4);

console.log(numbers);

Output:

[1, 2, 3, 4]

And our brain goes:

“???
Wasn’t this supposed to be immutable?”

Welcome to the philosophical side of JavaScript.


🧩 3. The Real Truth: What const Locks—and What It Doesn’t

Here comes the golden sentence. Memorize it:

const locks the variable’s REFERENCE.
Not its contents.


🔗 What Does “Reference” Mean?

In JavaScript, arrays are not the box itself—
they are the address of the box.

So when you write:

const numbers = [1, 2, 3];

What’s really happening is:

numbers → 📦 [1, 2, 3]

  • numbers = the address
  • [1, 2, 3] = the items inside

🧳 Time for an Analogy (JavaScript Loves These)

  • const numbers → the suitcase
  • Array elements → the clothes inside the suitcase
numbers.push(4);

➡ You’re not changing the suitcase
➡ You’re just adding another sock 🧦
➡ JavaScript says: “All good.”

But if you do this:

numbers = [10, 20, 30];

➡ You throw away the old suitcase
➡ And try to buy a new one

JavaScript responds:

“Hey! Stop right there. We said const.”


🚫 4. What You Can NEVER Do with a const Array

❌ 1. Reassignment

const fruits = ["apple", "banana"];

fruits = ["orange", "grape"];

This throws an error.
Why?

  • The reference changes
  • JavaScript hates that

❌ 2. Escape by Reassigning

const a = [1, 2, 3];
a = [];

Nope.
There is no escape 😄


✅ 5. So What IS Allowed with a const Array?

➕ Adding elements

const fruits = ["apple", "banana"];

fruits.push("orange");

📌 push → adds to the end
📌 Same reference, modified content


➖ Removing elements

fruits.pop();

📌 Removes the last element
📌 Still the same array


✏️ Modifying elements

fruits[0] = "cherry";

📌 Index-based editing is allowed


🔁 Using array methods

fruits.splice(1, 1);

📌 Slice, cut, rearrange as you like
📌 JavaScript won’t complain


🧠 6. “If It Changes Anyway, Why Not Use let Instead of const?”

Great question.
The answer: SECURITY 🔐

Consider this code:

const users = [];

function addUser(name) {
  users.push(name);
}

Here:

  • users is always the same list
  • You can’t accidentally write users = null
  • Anyone reading the code knows: “This array will always exist.”

In team projects, this saves lives.


🧊 7. “I Want It to NEVER Change”

Then it’s time to bring out Object.freeze.

const numbers = Object.freeze([1, 2, 3]);

numbers.push(4);
numbers[0] = 99;

Result:

  • In strict mode → ❌ error
  • Otherwise → silently fails

📌 freeze = a freezer bag
📌 You try to open it… but you can’t 🧊


⚠️ Warning: Freeze Is Shallow

const data = Object.freeze([
  { name: "Ali" }
]);

data[0].name = "Veli";

❗ This still works!

Because:

  • freeze only affects the top level
  • Inner objects are still mutable

That’s why:

“If you want total protection, you need deep freeze.”

(That’s advanced territory—we’ll skip it for now 😄)


🧪 8. A Real-World Project Example

const cart = [];

function addToCart(product) {
  cart.push(product);
}

function clearCart() {
  cart.length = 0;
}

Why is this good?

  • cart always keeps the same reference
  • The app doesn’t break
  • State management becomes easier

Modern frameworks like React and Vue love this pattern.


🎯 9. Professional Tips Corner 💡

✔ Defining an array? → think const first
✔ No reassignment needed? → don’t use let
✔ “This variable should always exist” → use const
✔ “I need to reset it” → change the method, not the reference


🧠 10. Short but Legendary Summary

  • const = fixed reference
  • Array contents = mutable
  • Reassignment = forbidden
  • Safe, clean, professional code

🚀 Final Words

In JavaScript, const says:

“The address I point to will never change.
What you do inside is up to you.”

Once you truly understand this:

  • Bugs decrease
  • Code becomes more readable
  • Seniors start nodding at you with respect 😄

Comments

No comments yet. Why don’t you start the discussion?

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir