If an object cannot be changed, we say that it is immutable. Strings are immutable, which means we cannot change the individual characters within a given string. While we can access individual characters using bracket notation, attempting to change individual characters simply does not work.
We attempted to change the value of the character at index 6 from
It is important to notice that immutability applies to string values and not string variables.
We can set a variable containing a string to a different value.
let nonprofit = "Launchcode"; nonprofit = "LaunchCode"; console.log(nonprofit);
In this example, the change made on line 2 is carried out. The difference between this example and the one above is that here we are modifying the value that the variable is storing, and not the string itself. Using our visual analogy of a variable as a label that “points at” a value, the second example has the following effect:
When the value of a variable storing a string is changed, the variable then points to a new value, with the old value remaining unchanged.
Check Your Understanding
pet = 'cat', why do the statements
console.log(pet + 's'); and
pet += 's'; NOT violate the immutability of strings?