Start learning free

LESSON 63 OF 671 · STRINGS I

String Immutability in JavaScript

Lesson

In JavaScript, 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);

would output:

Jello world

As you can see, the program executes but the string wasn't changed after all. Some languages like Python wouldn't even let this code run, but throw a TypeError. JavaScript is more permissive, which is not necessary a good thing.

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 JavaScript 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