Learn Introductory JavaScript by Building a Pyramid Generator

This is the code:

const character = "#";
const count = 8;
const rows = [];

for (let i = 0; i < count; i = i + 1) {
  rows.push(i);
}

When I console.log(rows) I get this: [ 0, 1, 2, 3, 4, 5, 6, 7 ]
But I thought when declaring a variable using const it becomes immutable and you can’t change its value… is there a difference between reassigning a value and whatever this is?..

The keyword const is a little misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

  • Reassign a constant value
  • Reassign a constant array
  • Reassign a constant object

But you CAN:

  • Change the elements of constant array
  • Change the properties of constant object
1 Like

Hey @itsxxtx

In JavaScript, the const keyword does indeed make the variable binding immutable, i.e. you cannot reassign a new value to the variable itself. But this does not imply that the contents of the variable are immutable, particularly when the variable is referencing a non-primitive type such as an object or an array.

  1. Reassigning the value means changing what the variable points to:
rows = [1, 2, 3]; // Error because `rows` is a constant and cannot be reassigned
  1. Mutating means changing the content or structure of what the variable points to:
rows.push(1); // Works fine because you're modifying the contents of the array, not reassigning the variable

Hope this helps :sparkles:

1 Like

Here is the link: JavaScript const

1 Like