My Palindrome Checker

Under a spoiler cut, obviously. I used a lot of variable names and made it longer that it needed to be, but I find this particular style helpful for debugging and just working through algorithms in general. If I were using the palindrome checker for a bigger project or working with a group of other people, I’d refactor my code to make it shorter. I console-logged every step but deleted that from the code so it’s a little more readable, LOL. I did include the set of instructions I gave myself at the top.

//Remove all non-alphanumeric characters, turn string to lowercase, turn string into array, reverse array, turn reversed array into string and compare original with reversed

function palindrome(str) {
  const alphanum = str.replace(/[^a-zA-Z0-9]/g, "");
  const simplified = alphanum.toLowerCase();
  const startArray = simplified.split("");
  const reverseArray = startArray.reverse();
  const reverseString = reverseArray.join("");
  if (reverseString === simplified) {
    return true;
  } else {
    return false;
  }
}

I’d appreciate any feedback on my code or advice on my coding practices in general. Thanks.

Having some extra variables is fine, especially if they can help document the code.

But then you do have to make sure the variable names are good, or at the very least, not misleading. You also have to consider if an array method you are using is mutating the array. For example, saving the result of a mutation to a new variable might be a bit misleading unless it is done on a temporary copy of the array.

Chaining too many methods can lead to code that is harder to read, but skipping a few intermediate steps by chaining methods can also in some cases increase the readability. It’s a balancing act and comes down to personal preference as well.

But you are right that starting out with each step first so you can log them can be a good idea. Then later you can chain them as needed.

1 Like

Thanks for the input. Since the array was changed here, I took out the extra variable for that and simply called it “array.” The names were more important for the strings since that was what I did the most work on and since the ultimate result for the palindrome checker depended on comparing two strings. For now, I’ve decided to keep my overall structure with each step on a separate line. The code isn’t particularly long, and seeing each step on a new line is helpful for my learning process (both in actually writing the code and reviewing it later).