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

Image of Timescale

πŸš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsβ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post β†’

Top comments (1)

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

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more