# How can I make this code more clear? (Basic Algorithm Scripting: Mutations)

Hi all,

I solved the ‘Basic Algorithm Scripting: Mutations’ challenge but I think my code looks messy and lengthy. How can I make it more clear and concise?

``````function mutation(arr) {
let newArr1 = arr[0].toLowerCase();
let newArr2 = arr[1].toLowerCase();
let newArr3 = newArr1.split('');
let newArr4 = newArr2.split('');
let i;
let newArr5 = []
for (i = 0; i<newArr4.length; i++) {
if (newArr3.indexOf(newArr4[i]) > -1) {
newArr5.push(newArr4[i]);
}
}
let newArr6 = newArr4.join('');
let newArr7 = newArr5.join('');
if (newArr6 === newArr7) {
return true;
}
return false;
}

mutation(["hello", "hey"]);
``````
1 Like

One way to make your code more readable is to use variable names which describe what is contained within them. For example, instead of using newArr1 and newArr2, you should rename them something which does not have Arr in it, because they are not arrays. You might rename newArr1 to charsToSearch and rename newArr2 to charsToValidate.

You could get rid of the newArr3 and newArr4 variables as it is not necessary to split the other variables into arrays. Why? Because you can use indexOf with strings the same way as you can arrays. This would also allow you to get rid of the line where you declare newArr6, because you could just reference the charsToValidate instead.

Lastly, instead of using a an if statement for the return of true and having the return false on the following line, you could simply return the comparison of the strings (currently represented by newArr6 and newArr7), because the express will still evaluate to the applicable Boolean value before it is returned.

2 Likes

Thank you, Randell! That is very helpful.

``````const mutation = ([first, sec]) => {
first = first.toLowerCase();
sec = sec.toLowerCase();
return sec
.split('')
.filter(it => first.includes(it))
.join('') === sec;
}
``````

Hey @caroham29!

Welcome to the forum!
I have edited your post to include [spoiler] tags. Whenever you provide solutions in the forum please wrap them in those spoiler tags first.

Thanks!