-4
function home() {
  const list = ['john', 'adele', 'hary']; list.push('tiger');
  return list;
}
home() //["john", "adele", "hary", "tiger"]

push method is available and also, list[0] = "abc" is available

In JS, const keyword is different to Java or CPP??

  • 11
    No reassignment !== no mutation – CertainPerformance Jun 07 '18 at 07:25
  • With `list[0]` you are not mutating whole array, just assigning value to some index. Again with `Array.push` you are not mutating whole array, just you are adding something to the end of array. – Efe Jun 07 '18 at 07:27
  • You might be looking for [Object.freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) – Paul Jun 07 '18 at 07:29

3 Answers3

1

With a const declaration, you can't reassign the variable but you can mutate it, which is what happens with the Array.prototype.push method.

You won't be able to do like

function home() {
  const list = ['john', 'adele', 'hary']; 
  list = list.concat(['tiger']); // this is reassignment and hence will fail
  return list;
}
home()
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

The documentation states:

  1. constant cannot change through re-assignment
  2. constant cannot be re-declared

You are not reassign value and not redeclare, therefore it's legal.

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
0

It's possible to push items into the array. However, assigning a new array to the variable throws an error - Uncaught TypeError: Assignment to constant variable.

list = ['man','woman']; //ERROR IN YOUR CASE
Negi Babu
  • 507
  • 4
  • 11