Immutable Primitive Values and Mutable Object References
There is a fundamental difference in JavaScript between
primitive values (undefined,
null, booleans, numbers, and
strings) and objects (including arrays and functions). Primitives are
immutable: there is no way to change (or “mutate”) a primitive value.
This is obvious for numbers and booleans—it doesn’t even make sense to
change the value of a number. It is not so obvious for strings,
however. Since strings are like arrays of characters, you might expect
to be able to alter the character at any specified index. In fact,
JavaScript does not allow this, and all string methods that appear to
return a modified string are, in fact, returning a new string value.
For example:
vars="hello";// Start with some lowercase texts.toUpperCase();// Returns "HELLO", but doesn't alter ss// => "hello": the original string has not changed
Primitives are also compared by value: two
values are the same only if they have the same value. This sounds
circular for numbers, booleans, null, and undefined: there is no other way that they
could be compared. Again, however, it is not so obvious for strings.
If two distinct string values are compared, JavaScript treats them as
equal if, and only if, they have the same length and if the character
at each index is the same.
Objects are different than primitives. First, they are mutable—their values can change:
varo={x:1};// Start with an objecto.x=2;// Mutate it by changing the value of a property ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access