JavaScript String Immutability

Shawn Rice
JavaScript in Plain English
2 min readDec 15, 2021

--

I see much confusion regarding string immutability, and I thought I would do my best to clarify what that means for the confused.

It is often pointed out to new programmers that “strings are immutable.” However, just stating this fact doesn’t clarify how it applies functionally when we are writing code. Often when beginners are learning, “changing” strings happens all the time. You learn how to perform operations and slices; re-declaring the old variable to the new string.

This is where it can get confusing because if you don’t really understand what’s happening, it’s easy to think that we’re actually changing the original string. But that’s just it, you’re not changing the original string; you’re changing the variable. You perform an operation on the original string, which will return the result of the operations performed on the original string without changing the original string.

Understanding that, it becomes more clear why you have to reassign the variable (or create a new one) every time you want to store the result of your operations on a string.

Say you have a variable let x = 'string' — Even if you do x[0] = 't' you will not change x to 'ttring' as you might expect. x will still be equal to 'string'. However, this doesn't mean you can't have your desired outcome. Say you want to pad a string with something. There is a handy tool in JavaScript `` template literals; they allow you to construct strings using variables. So, if you have x and you want to add '*' to the start and end of x, as well as replace x[0] with 't' you can do x = `*t${x.slice(1)}* and now x = '*ttring*'

What happens here is that we are assigning x to the value of a slice of the original string starting at index of 1 'tring' with ‘t’ before that slice, and '*' on both sides.

In the end, we still have never changed the original string; x now points to a new and different string that was the result of the operations performed on the prior value of x(the original string). The result is the same variable holding an entirely different string, with the original string now lost or junk-collected (if not stored somewhere else). And even though it may be lost, functionally speaking, we never changed the original string.

More content at plainenglish.io.

--

--