1

For JavaScript in most browsers*, you can read a character from a String by treating it like an Array. However, in all the browsers I've tried (IE9, Chrome, Firefox), you can't write to it like an Array.

For example:

var string = 'hello world';
alert(string[0]);//alerts 'h'
alert(string);//alerts 'hello world'

string[0]='j';
alert(string[0]);//alerts 'h'
alert(string);//alerts 'hello world'

This has repercussions for more than just JavaScript developers:

jelloPeople.roam();


Does anybody know the reasoning behind this?


For example, I've looked at Mozilla's documentation, and they allude to it but don't give an explanation:

    "..trying to set a character via indexing does not throw an error, but the string itself is unchanged."

Bottom Line: It is strange and confusing to me that some array properties were given to Strings and not others.

UPDATE:

Ok, so JavaScript Strings are immutable objects, but why? It seems like operations such as the above would be faster if they weren't immutable (change 1 character as opposed to making a new 11 character string). In fact, I don't see a case with String functions where performance would be impacted negatively if they weren't immutable, but I see several where performance would be improved. Also, there is no true multi-threading in JavaScript, so no advantage to immutables there.

(removed and will research this and possibly ask in a new quesion)


*Not IE 6 or 7

4
  • jelloPeople.roam()? What does that mean? Aug 3, 2011 at 15:34
  • 1
    Read about immutability -- good stuff to know.
    – Ray Toal
    Aug 3, 2011 at 15:35
  • @Vivn Paliath: Sorry, it was a bad attempt at humor.
    – Briguy37
    Aug 3, 2011 at 15:35
  • It's fairly common for strings to be immutable objects
    – Sam Dufel
    Aug 3, 2011 at 15:35

2 Answers 2

4

This simply because javascript strings are immutable by design; once created they cannot be changed.

4

I think it might be because strings in JavaScript are immutable. Notice that every string function doesn't actually change the string itself, but returns a new one. This is the same for changing characters directly, it wouldn't work with an immutable model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.