Javascript Palindrome Problem

Here are a few solutions to the palindrome problem (a palindrome is a word that is the same spelled backward or forwards — like “racecar.” The objective is simply to return true if the word is a palindrome or false if it is not a palindrome.

The solutions to this are pretty simple.  I just need to take the result from the Reverse String problem and compare it to the original string.

One thing I learned doing this problem is the array.prototype.every() method.  The every() method tests whether all the elements in an array meet a certain criteria.  If all the elements meet the criteria, it returns true, if not, it returns false.  I check the first character against the last character, then the second character against the second from the last character, etc.  Checking the last half of the word is redundant, but it is an interesting alternative solution.

// SOLUTION 1 -- using array.prototype.reverse() method
function palindrome(str) {
   const reverse = str.split("").reverse().join("");
   return str === reverse;
}

// SOLUTION 2 -- using for...of
function palindrome(str) {
   let reverse = '';

   for (let character of str) {
      reverse = character + reverse;
   }
   return str === reverse;
}

// SOLUTION 3 -- array.prototype.every() method
function palindrome(str) {
   return str.split('').every((char, i) => {
      return char === str[str.length - i -1];
   })
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *