Three ways to check for palindromes in JavaScript

domazet93

Toni Domazet

Posted on September 11, 2018

Three ways to check for palindromes in JavaScript

A palindrome is a word or a phrase that is the same whether you read it backward or forwards, for example, the word 'level'.

I'm going to create three different functions that are doing the same job - palindrome check for a passed string. I will mesure time of function execution to see which one of this function gives the best performance using performance.now() Web API method.

Create an array

isPalindrome = (string) => {
  string = string.toLocaleLowerCase();
  return Array.from(string).toString() === Array.from(string).reverse().toString()
}

//0.52 ms
Enter fullscreen mode Exit fullscreen mode

Array object has a lot of useful methods - one of them is reverse(), but first, we need to create an Array from a string. After reverse, the first array element becomes the last, and the last array element becomes the first. We can't do check now, because condition will always be false as they're objects with different locations in memory. toString() method will return a string from our arrays.

Recursion

isPalindrome = (string) => {
  let strLen = string.length;
  string = string.toLocaleLowerCase();

  if (strLen === 0 || strLen === 1) {
    return true;
  }
  if (string[0] === string[strLen - 1]) {
    return isPalindrome(string.slice(1, strLen - 1) );
  }  
  return false;
};

//0.30 ms
Enter fullscreen mode Exit fullscreen mode

Recursion is a process when a function calls itself to solve a problem. In our code, function is called until string completes (empty string or one char left), or if condition falls. First check for first and last char in the string, then if they are same do the same thing for a substring with first and last char removed, and so on...

for - loop

isPalindrome = (string) => {
  let strLen = Math.floor(string.length / 2);
  string = string.toLocaleLowerCase();

  for (let i = 0; i < strLen; i++) {
    if (string[i] !== string[strLen - i - 1]) {
      return false;
    }
  }
  return true;
}

//0.20 ms
Enter fullscreen mode Exit fullscreen mode

for loop starts with the check for first char of the string and last char of the string. If it's equal, continue iterating through the string until the string reaches the center.

I like the first approach as it's clean and simple, but from a performance view, it gives us the worst result, where simple for loop is more than twice time faster.

💖 💪 🙅 🚩
domazet93
Toni Domazet

Posted on September 11, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

8.9 Parens
javascript 8.9 Parens

November 5, 2019

8.7 Permutations Without Dups
javascript 8.7 Permutations Without Dups

November 1, 2019