1

So I've tried to use the map() method as follows:

words = ["One", "Two"];
words = words.map(function(currentValue)
    {
        alert(currentValue[0]);//Output: O Then: T
        currentValue[0] = "A";
        alert(currentValue[0]);//Output: O Then: T
        return currentValue;
    });

Why is it that currentValue[0] is not getting assigned the value "A"?!?

John Pizzo
  • 327
  • 1
  • 5
  • 9
  • See http://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript – Peter Dec 09 '14 at 12:58

3 Answers3

3

Your attempting to assign to a string at a specific position via its index, this is not possible as Strings are immutable. If you want to change a string you need to create a new one.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • Can you explain how alert(currentValue[0]) alerts the character? I mean here the immutable String is treated as an array? – Sampath Liyanage Dec 09 '14 at 13:01
  • You can *read* using the `string[pos]` syntax but you cannot *write* to the string - if you could do that you would have a string that contained a different value from the one it was created with, and JavaScript disallows this (immutability). – Alex K. Dec 09 '14 at 13:06
1

As Alex K correctly points out, strings are immutable and you cannot modify them.

Since you are using a .map(), the thing to do here is just construct a new string and return that:

var words = ["One", "Two"];

words = words.map(function (currentValue) {
    return "A" + currentValue.substring(1);
});

console.log(words); // outputs ["Ane", "Awo"];

As a rule of thumb, you should not try to use .map() to modify existing values. The purpose of .map() is to produce a new set of values, and leave the original ones untouched.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

In JavaScript String is the primitive type, so you cannot mutate it.

String , Number , Boolean, Null, Undefined, Symbol (new in ECMAScript 6) are primitive types.

ray
  • 145
  • 9
  • Wait really? Does that mean String is not an Object?! – John Pizzo Dec 09 '14 at 15:26
  • That's correct. `"" instanceof Object` produces `false`. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Distinction_between_string_primitives_and_String_objects – JLRishe Dec 09 '14 at 15:48