DEV Community

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

Posted on

1

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

๐Ÿ‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Communityโ€”every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple โ€œthank youโ€ goes a long wayโ€”express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay