Understand String Immutability i didn't understand

Tell us what’s happening:

Your code so far


// Setup
var myStr = "Jello World";

// Only change code below this line

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability

To change the myStr variable you need to set it to a new string:

myStr = "Hello World";

Once you assign a string that string can not be changed in memory.
you can access i any charachter of it separately :
myStr[1] = e
but you can not changed it because it can not be changed in the memory it is preserved .

I still don’t get it… can u please describe this thing???

It’s pretty clearly explained in the challenge description I believe.

The following code:

> var myStr = "Bob";
> myStr[0] = "J";
  1. Contents, meaning individual elements (in this case = characters of the string) can’t be changed.

That’s what immutability is - you can’t modify the parts of it. Let’s take a loot at an object:

const myObject = {
  name: `aziztareq295`
}

Objects can be mutated. You can go ahead and write myObject.name = "New Name". It’s still going to be the same object, but its content (name property) will be changed to “New Name”.

Which brings me to the 2nd point:
2. While you can’t mutate a variable containing a string, you can assign it a completely new value.

Like this:

var myString = "This is my string!" // declaration

myString[1] = "G"
// ^^ trying to mutate(change the second letter). This won't work. myString is still "This is my string!"

myString = "This is a new string!"
// ^^ new value is assigned to myString. myString is now "This is a new string!"

I hope it makes things a bit clearer.

1 Like

Thank You sir…:slightly_smiling_face:

:white_check_mark: I have solved this and I hope it helps you :white_check_mark:


// Setup
var myStr = "Jello World";

// Only change code below this line

myStr = "Hello World";