Please help me understand this! Basic JavaScript - Understand String Immutability

Tell us what’s happening:
I don’t understand why it keeps saying
TypeError:
Attempting to assign to randomly property
Your code so far

// Setup
let myStr = "Jello World";

// Only change code below this line
myStr = "Hello World"; myStr[0] = "H"; // Change this line
// Only change code above this line

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15

Challenge: Basic JavaScript - Understand String Immutability

Link to the challenge:

This is not a legal move. Delete this block of code.

I think you better re-read this challenge as you seem to have completely missed the point.
Start from the top where it says

In JavaScript, String values are immutable, which means that they cannot be altered once created.

But isn’t the whole point of the challenge is to make the first letter in the string become H? I’m so confused now :smiling_face_with_tear:

But it says that the value can be reassign and I feel like I’m doing what the example is doing :face_exhaling:

OMG!!! Thank you so much it works :laughing:

Yes you are right. But you cannot do something which is not possible. Once you create a string you cannot change it.

But did you understand why it worked? Otherwise it is of no use. :smiling_face_with_tear:

I think I understand now. The [0] = ‘H’ is supposed to be the outcome of code after I modify it and the challenge didn’t asked me to put that as part of the code. All I need to do is assign the correct value to the variable to make sure the first letter is H right? :see_no_evil:

1 Like

No. You really need to reread this challenge,

strings are immutable, you can only assign it again with new value, delete myStr[0] = “H”

Just to reiterate, in JS you cannot change individual letters of strings like that. In some languages you can, but not in JS. In JS, you either have to give it a complete, new string … or you need to build the new version of the string out of pieces of the old string, creating a new string. But the point is that it is “immutable”, you cannot “mutate” it. Once it is saved in memory, you cannot change it, only replace it.

This is actually true of all primitive types, but it’s mainly an issue with strings. Later on, there will be times when it is best to treat reference types like this, too, like with arrays and objects.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.