Start learning free

LESSON 65 OF 675 · STRINGS I

String Immutability in TypeScript

Lesson

In TypeScript, strings are immutable, which means that they cannot be altered once created.

For example, the following code:

let message = "Jello world";

message[0] = 'H';

console.log(message);

is rejected twice. The compiler reports error TS2542: Index signature in type 'String' only permits reading. and, when the compiled JavaScript runs anyway, the assignment throws:

TypeError: Cannot assign to read only property '0' of string 'Jello world'

As you can see, the string can't be changed: both the compiler and the running program refuse the assignment.

As a programmer, I'd rather be told when I made a mistake early on so I can fix it, instead of running into problems later on and not knowing what the root of those problems is.


Variable can still be changed:

Note that this does not mean that message cannot be changed, just that the individual characters of a string literal cannot be changed.

"Jello world" is a string literal that TypeScript stores in memory, while message is a variable that refers to that string literal.

When we do message[0] = 'H', we are trying to alter the string literal "Jello world", which is not allowed.

But like any other variable, message can be changed by reassigning it with a new string, like this:

let message = "Jello world";

message = "Hello world";

console.log(message);

This code would output:

Hello world

Instead of trying to alter the first string, this code now creates a new one ("Hello world"), stores it in memory and tells message to refer to this new string.


Assignment
Follow the Coding Tutorial and let's practice with string immutability!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check