Const and Arrays

Am I correct in understanding that since we do not want to mutate arrays in JavaScript that best practice means we should always declare arrays as a const variable?

Yes, you are correct.

1 Like

You got your answer. But here are my two cents as well.

Iā€™d say it is the complete opposite. Because you either do array mutation or use non-mutating methods and syntax there is really never a good reason to redeclare or reassign the identifier containing an object, so it might as well be a constant.

If you want to prevent mutation you can freeze the object.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Object.freeze(numbers);
numbers.push(11); // TypeError: Cannot add property 10, object is not extensible

Edit: I just realized that the error message might be a bit confusing. The property 10 it is referring to is the index at which the number was attempted to be pushed (it is not related to the values).

Here is an object example as well.

const user = {
  name: "John",
  age: 30,
};

Object.freeze(user);
user.age = 40;
console.log(user.age); // 30
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.