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"?!?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain how alert(currentValue[0]) alerts the character? I mean here the immutable String is treated as an array?
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).
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.

1 Comment

Good to know about that rule of thumb. Thanks
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.

2 Comments

Wait really? Does that mean String is not an Object?!
That's correct. "" instanceof Object produces false. See: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.