Mutation - Question on code conventions

Hi everyone! I am curious…

My code works (see base of post for it), but it has raised a question.

Would it be better to use the .toLowerCase() method on the two strings before the for loop - so the method only runs 1 time for each variable instead of multiple times within the loop (possibly making load times longer)?

So, if I instead did:
var string1 = arr[0].toLowerCase();
var string2 = arr[1].toLowerCase();
and used the var names in the for loop instead of arr[0].toLowerCase() and arr[1].toLowerCase() , would that be better? Or no difference?

This is my code::

function mutation(arr) {

  for (let i=0; i<arr[1].length; i++) {
    var checker = arr[0].toLowerCase().indexOf(arr[1].toLowerCase()[i]);
    if (checker < 0) {
      return false;
    }
  }
  //loop finished without false (no -1 from the indexOf search) -> all letters were matched.
  return true;
}
mutation(["hello", "hey"]);

Thanks for your help :slight_smile:

Hi. In my opinion it’s generally better to move calculations that return a constant value out of the loop. You get the same result for every iteration, so why bother recalculating it every time? You can also potentially save time by doing this.

1 Like