DEV Community

Cover image for Episode 01 - How to check the Palindrome in JavaScript
Vigowebs
Vigowebs

Posted on

Episode 01 - How to check the Palindrome in JavaScript

One of the famous JavaScript interview questions. How to check the palindrome in JavaScript. A palindrome is a word or phrase that reads same in the reverse order also. Some of the examples are civic, rotor, noon, level, mom, madam and racecar.

Now lets see how to solve this in JavaScript. Most of the programmers would go on in a straight-forward way and uses for loop to solve this. Lets explore that way first:

const isPalindrome = (string) => {
  const length = string.length;
  if (!string) return false;
  for (let i = 0; i < length; i++) {
    if (string[i] !== string[length - i - 1]) {
      return false;
    }
  }
  return true;
}

// isPalindrome('madam') prints true
// isPalindrome('hello') prints false

Enter fullscreen mode Exit fullscreen mode

This is good and solves the problem at our hand. But can we improve anything in this program. If you see, to confirm if the string is a palindrome or not, we only need to check half of the string. For example, if the string is 10 characters in length, we can check and compare only 5 characters to verify the palindrome. If the string length is an odd number, lets say 5 characters, we need to check only 2 characters. The string is palindrome regardless of the mid character if rest of the characters

Now applying this to our program, we can reduce the loop iteration to half.

const isPalindrome = (string) => {
  const mid = Math.floor(string.length / 2);
  const length = string.length
  if (!string) return false;
  for (let i = 0; i < mid; i++) {
    if (string[i] !== string[length - i - 1]) {
      return false;
    }
  }
  return true;
}

// isPalindrome('rotor') prints true
// isPalindrome('hello') prints false
Enter fullscreen mode Exit fullscreen mode

As usual this is one of the way to solve the problem. Comment below your solution.

Check Palindrome in our YouTube

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited
const isPalindrome = ([...s]) => ''+s == s.reverse()
Enter fullscreen mode Exit fullscreen mode