Understand String Immutability

In this challenge it has me change this code

// Setup
var myStr = "Jello World";

// Only change code below this line

myStr[0] = "H"; // Fix Me

to do this it has me add

myStr = "Hello World";

why would i do this and not just change the J to an H in this first place seems like i am doing extra work when i can just go back in and change one letter.

Hey, the example is trivial, but there might be a situation that you might want to change a letter at a specific index.

Well, because you can’t change it in place, because the string is immutable. So changing just the first letter becomes some extra work in itself (some slicing and dicing is required, creating new, shorter strings and then gluing them back together), and that’s probably why the simple replacement of complete string was used for this example.

But I think you can do it any way you want, as long as the final value of myStr is “Hello World”.

Actually you can’t. Read the description of the challenge:

individual characters of a string literal cannot be changed

And the tests make sure you don’t change the //Setup

// Setup
var myStr = "Jello World";

// Only change code below this line

myStr = "Hello World";
myStr[0] = "H";

THIS IS WHAT I TYPE IN BUT IT DOESN’T WORK. IT SAYS: type error. Does anybody know what I did wrong?

Hi,

Have you found the solution?

1 Like

Yes! thank you. It turned out to be incredibly simple. my mind went blank after too many hours behind the computer…

Well, actually I was gonna ask your help, cause my code is exactly same as yours and I get the same error. I just don’t get what I did wrong.

Could you share your solution please?

Thanks in advance.

ar myStr = “Jello World”;

// Only change code below this line

myStr = “Hello World”; // Fix Me

1 Like

It is misleading. You change
myStr[0] = “H”;
to:
myStr = “Hello World”;

Challenge is telling you something is impossible so you are suppose to figure out (just remove the impossible part).

2 Likes

Mhm, as the description of the challenge says, strings are immutable even if they’re iterable like arrays. But strings being iterable can be good because it means you can do this.

function changeAtIndex(str, index, newChar) {
  return !(index >= str.length - 1 || index < 0)?
    str.slice(0, index) +newChar + str.slice(index + 1) :
    str;
}

Or use the String.prototype.replace method with or without a Regular Expression.
Or just split the string, change something, and join it back.

you can also do this:

var myStr = “Jello World”;
var text;
text = myStr.slice(1,myStr.length);
text = “H”+text;
myStr = text;