I’m just reading JavaScript: The Definitive Guide by David Flanagan. I’m really enjoing and I’m happy my first Javascript book is this one. 🙂
However, I can’t make much sense of this paragraph (3.7 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.
Probably I’m just missing something due to my lack of CS background (self-taught and all…), but could anybody help me shed some light on it?
Particularly the part I’ve made emphasized: Why it wouldn’t make sense to change value of a number?
My ideas so far:
- maybe he’s strictly distinguishing between concepts of (what in other language could be called)
“variables” and “values”. Then OK, it really does not make sense to change value of 3 to value
of 4 (so that3 == 4), but such explanation fails on the next sentence: such operation does
not make any more sense for strings than for numbers…?
You’re right that it doesn’t make sense to change the value of a string literal — which is what he is in fact saying; he just says that it might not be as obvious as the
3 == 4case, since you can reference individual characters in a string (and might then think you can change the string by changing a particular character).Consider the example:
Intuitively this seems as if it would capitalize the word, but the string is immutable so that won’t work.
Checking the output of
swe still see:s > 'hello world'