I was recently working on a Leetcode question and stumbled across something that I at first thought was strange, but then after looking at it for a second, realized it might have to do with JavaScript String immutability.
I wanted to ask and see what the community thought.
Here's a snippet of some code:
var keys = function(words) {
for (var i = 0; i < words.length; i++) {
// With lower, ['hello', 'alaska', 'dad', 'peace']
var lower = words[i].toLowerCase();
console.log(`Word is ${lower}`);
}
}
keys(['Hello', 'Alaska', 'Dad', 'Peace']);
Does lower work because since JS strings are immutable, we'd have to make a copy of the string first in order to use it elsewhere with the applied transformation (making the string lowercase)?
var keys = function(words) {
for (var i = 0; i < words.length; i++) {
// Without lower, ['Hello', 'Alaska', 'Dad', 'Peace']
words[i].toLowerCase();
console.log(`Word is ${words[i]}`);
}
}
keys(['Hello', 'Alaska', 'Dad', 'Peace']);
Does this not work because again, strings are immutable so a transformation cannot be applied?
Thanks
toLowerCase()simply returns a new string. You don't have to make a "copy" of the original string. Besides, since strings are immutable, doing a copy is a) not necessary and b) you wouldn't be able to tell whether you actually have a copy or not.vardeclaration, which is redundant because the variable is already declared.'Dad':)