+ 2
what exact is immutability?
it's said that string values are immutable ie the value can't be cahanged but when the string method .replace() and others the string value is changed. how then is a string value immutable?
4 Réponses
+ 4
So yeah, this is confusing, I know.
Most languages say “Strings are immutable” or in other words “you can’t change a string”, and then, literally the lesson after or the next page they go and explain different ways of how to “change” strings.
The thing is, it only looks as if strings are changed/altered.
Every function/method that “changes” a string doesn’t actually change it. It reads the string from the original memory location, copies it, changes/does the thing you want with it, and then stores it as a new string in a new memory location.
Whether or not it then assigns it to the same variable is up to the language and differs.
All and all, if it says “immutable”, that is what usually happens in one form or another :)
+ 4
The method returns a new string
+ 2
I don't how exactly .replace() works yet but.. if you declare a variable with let and then later on in the code you declare the same variable again by mistake or otherwise it's going to overwrite the previously stored value, however if it's declared with const and you do the same, it's gonna throw you an error. But it can be said shortly immutable kind of a fancy word for unchangeable.
+ 2
i had forgotten that all the string method returns a new string or so instead of changing the original string value.