JavaScript strings - a followup
Having played around with the JavaScript string type some more, I think I understand why it acts as it does. I'm a Perl monkey normally, so I'm not used to the concept of immutable strings, but JavaScript strings are immutable. Playing with the ===
operator (approximately, 'is this the same object') gives:
js> "a" === "a";
true
js> "a" + "b" === "ab";
true
js> "ab".replace(/./, "c") === "cb";
true
but
js> new String("a") === new String("a");
false
If strings were to magically upgrade themselves to objects, they'd change behaviour - previously equivalent strings would suddenly not be equivalent. Likewise, suppose this worked:
var a = "string";
var b = "string";
a === b; # true
a.foo = 1;
Shoud a
still be equivalent to b
? If not, a
clearly isn't immutable, as we've changed it. But if it is, then we've chanaged b
at a distance - it's grown a foo
attribute.
Still all very annoying, of course, but I understand why now.