Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain why it "doesn't even make sense to change the value of a number"

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 that 3 == 4), but such explanation fails on the next sentence: such operation does not make any more sense for strings than for numbers...?
like image 682
Alois Mahdal Avatar asked Dec 27 '22 19:12

Alois Mahdal


2 Answers

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'

like image 137
nbrooks Avatar answered Dec 29 '22 08:12

nbrooks


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.

like image 30
Sebastian Paaske Tørholm Avatar answered Dec 29 '22 10:12

Sebastian Paaske Tørholm