Why some functions like toLowerCase()
when used on a string need to be assigned a new variable, but other functions like sort()
, reverse()
, or pop()
do not when used on an array?
For example, the code below is wrong:
var str = "Hello World";
str.toLowerCase();
but the code below is correct:
var arr = ["This","is","my","array"]
arr.sort();
I am reading that when using toLowerCase()
on a string, I must have the code written like this:
str = str.toLowerCase();
Because strings are immutable in JavaScript, which means you cannot change them. Every time you try to modify a string, you are effectively creating a new string with the changes.
So when you do str.toLowerCase();
, it's not modifying str
, it is actually making a copy of it with the lowercase of the letters.
The array is different because it is a list of references to the array items. You can change each item separately from the other items arr[5]=11
. You can also add or remove an item. The sort()
and reverse()
functions re-arrange the items in the array.
By the way, this concept is not unique to JavaScript. Many other modern languages also make strings immutable (perhaps all languages that have String
as a built-in type).