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:
3 == 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 == 4
case, 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:
var s = 'hello world';
s[0] = 'H';
Intuitively this seems as if it would capitalize the word, but the string is immutable so that won't work.
Checking the output of s
we still see: s > 'hello world'
It's exactly how you intrepet it. It would not make sense to change the value of 3, such that 3 == 4
, for instance.
As far as strings are concerned, mutability of their values is seen in some languages like C, but not in others like Java. As such, it's not necessarily as readily apparent that they're immutable. There are arguments for and against either choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With