However, I can't make much sense of this paragraph (3.7 Immutable Primitive Values and Mutable Object References):
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 = '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.
Basically, you have a stronger grasp of the distinction than the author, or at least than the author gives you credit for. Your "ideas so far" is exactly right, but he thinks that many new users expect to be able to change string primitives, too. You don't, which means your expectations match up with how the language actually behaves, rather than with how he thinks you'll expect things.
©2020 All rights reserved.