User 5842
User 5842

Reputation: 3029

JavaScript String immutability

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

Upvotes: 1

Views: 1350

Answers (1)

Barmar
Barmar

Reputation: 781088

toLowerCase() doesn't modify the string it's called on. Since strings are immutable, it couldn't do so. But even if they were mutable, it's just not what the function is defined to do. It returns a new string containing the lowercase version of the original string.

It's analogous to the slice() method of arrays. Arrays are mutable, but slice() returns a new array containing the specified sub-array, it doesn't modify the original array (that's what splice() does).

So if you want to do anything with that new string, you need to assign it somewhere, pass it as an argument to a function, or call some other method on the result.

If you don't want the lower variable, you can write:

console.log(`Row is ${row[i].toLowerCase()}`);

Upvotes: 3

Related Questions