“It’s important to know that in JavaScript, strings are immutable”
When learning JavaScript, you must have come across this a dozen times. But what does it really mean? How are they immutable? All of that confusion and more will be addressed in this article.
According to Cambridge dictionary, immutable means “not changing or unable to change”.
Immutable in JavaScript simply means you can’t change the value of the data. Immutable data types includes strings, numbers, boolean, null, undefined, bigint. Any operation you do that appears to modify the data isn't really modifying it but creating a new one with that modified outcome.
Let’s start with this example:
let age = 21
age = 16let age = 21
age = 16The normal idea is “I have an age container that stores the number 21 and now I am changing that age container to store 16 instead of 21”. But that isn't what’s Happening.
What’s happening is a new storage box that contains 16 is created. Which means the age container containing 21 still very much exists but it’s not our age container anymore.
Another example:
let name = "Bridget"
console.log(name[0])
//console: "B"let name = "Bridget"
console.log(name[0])
//console: "B"The console prints “B” which is the first letter (zero index) of the value Bridget.
Now let’s try changing the first letter to D
name[0] = "D"
console.log(name[0])
//console: "B"name[0] = "D"
console.log(name[0])
//console: "B"The console still prints B, because the value wasn’t changed. The string “Bridget” has been created, it can’t be modified. The values for primitive types are immutable, it’s just the variable that is reassigned to a different value.
let greeting = " Hello world! ";
console.log(greeting);
//console: " Hello world! "
greeting.trim()
console.log(greeting)
//console: " Hello world! "let greeting = " Hello world! ";
console.log(greeting);
//console: " Hello world! "
greeting.trim()
console.log(greeting)
//console: " Hello world! "Greeting in the console still remains “ Hello world! “
Nothing changed, to get the result of greeting.trim() using our previous analogy, you have to create a greeting container pointing to the new string.
greeting = greeting.trim()
//console: "Hello World!"greeting = greeting.trim()
//console: "Hello World!"