Introduction to Strings - What Is a String in JavaScript, and What Is String Immutability?

Tell us what’s happening:

Why do you say that a string is immutable and cannot be changed and then immediately show how it can be changed in the same way a let variable can be re-assigned?

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:145.0) Gecko/20100101 Firefox/145.0

Challenge Information:

Introduction to Strings - What Is a String in JavaScript, and What Is String Immutability?

Hi @bkarlan

Since strings are immutable, we can’t update the first string directly. That is why we are assigning a new string to the developer variable.

let str = 'Hi';
str[1] = 'y';

Since strings a immutable, once they are created, you cannot directly modify them.

The above code will result in an error.

However, the value of a variable can be reassigned.

let one = '1';
one = '2';

The variable one now contains the value '2'.

Happy coding

Further to the above example, here is a direct comparison between immutable data type (like String) and mutable data type (like Array)

let myArray = ['C', 'A', 'T'];
myArray[0] = 'B';
console.log(myArray); // outputs ['B', 'A', 'T']
let myString = 'CAT';
console.log(myString[0]); // outputs 'C'
myString[0] = 'B'; // this would not be possible and throws error
console.log(myString); // outputs 'CAT'

So, as you can see the array is mutable as you can modify an element in it, but a string can not be internally modified the same way. And you can only assign a completely new string to a variable.

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