Value vs. Reference with ES2015
Value vs. Reference with
There’s a small piece of the discussion of
const that was left out in the related previous lesson. We haven’t discussed how it works with objects. To truly understand that, we first needed an understanding of value vs. reference in JS. With that understanding, we can now finish our discussion of
Objects are mutable
const, with primitives, once a value is assigned to a constant variable, that variable is immutable. It cannot be changed.
With reference types, namely arrays and objects, it is the reference that cannot be changed. Writing
const arr = ; means that
arr always has a reference to the array that was just created.
Unlike primitives, the array itself is mutable and can be manipulated. Values can be inserted, removed, sorted, etc. Anything can be done to it. We just can’t reassign
arr to a different reference or value.