JavaScript ES6 const Keyword Allows Changes

The ES6 JavaScript const keyword prevents re-assignment of a reference, but it does not actually prevent data modification of any object being referenced.

Of course, a primitive value declared const cannot be changed:

> const pi = 3.1415926
> pi = 3
TypeError: Assignment to constant variable.

However, objects declared with const can still have their properties changed:

const myObject = {
  a: 5, 
  b: 10, 
  c: 15
} 

myObject.b = -1 // no error

console.dir(myObject)

Result:

{ a: 5, b: -1, c: 15 }

Similarly, arrays declared with const in ES6 can be edited! They simply cannot be re-assigned.

const arr = [1, 2, 3, 4, 5]

a[1] = -1 // this is fine

console.dir(arr)

Result:

[1, -1, 3, 4, 5]

Using methods to manipulate the const array is still allowed:

const arr = [1, 2, 3, 4, 5] 

arr.pop() // allowed

console.dir(arr)

Result:

[1, 2, 3, 4]

The following use of the delete operator is ok with const as well:

const arr = [10, 20, 30]

delete arr[1] // works

console.dir(arr)

Result:

[10, <1 empty item>, 30]

Note that delete leaves gaps in the array; for objects it will leave null.

Countless more examples are possible but the key point is: arrays and objects being referenced by a const variable can still be mutated.

Leave a Reply

Your email address will not be published. Required fields are marked *