0

When I set const value for arrays, I can change it later. why is there such a thing (google translate) Shouldn't the value I assign const throw an error?

const values=['a','b','c'];
values[0]='aaa';
console.log(values[0]);
  • const cannot be reassign const values, but we can modify the value at specific indexes or keys – Faizal Hussain Jul 06 '22 at 12:40
  • Try doing only `values = something` , you will see that it throws an error – aca Jul 06 '22 at 12:40
  • You can't assign another array to the variable `values` but `const` does nothing to prevent it's value from being changed. How can it? You could assign a shared reference to a const variable and assign it somewhere else – mousetail Jul 06 '22 at 12:40
  • You can use `Object.freeze()` to prevent modifications of the array itself. Again it will apply only to the array not it's elements, which can still be modified. – mousetail Jul 06 '22 at 12:42
  • @FaizalHussain No, assigning to a element of a frozen array will be ignored silently – mousetail Jul 06 '22 at 12:45
  • @FaizalHussain "*freeze will prevent push and pop , but still can be modified by arr[0] = 9*" [No, that is incorrect.](https://jsbin.com/rumogik/1/edit?js,console) – VLAZ Jul 06 '22 at 12:45
  • yes , it just doesn't throw any errors – Faizal Hussain Jul 06 '22 at 12:48

0 Answers0