How to Check for Palindromes in JavaScript

How to Check for Palindromes in JavaScript

Ferenc Almasi β€’ Last updated 2021 January 27 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

A palindrome is a sequence of characters that reads the same backwards as forward, such as "noon" or "level".

To check if a word is a palindrome, we can create a function for it, the implementation can vary, but probably the shortest solution is using a combination of split, reverse and join:

Copied to clipboard! Playground
const isPalindrome = str => str === str.split('').reverse().join('');

isPalindrome('noon');  -> true
isPalindrome('moon');  -> false
isPalindrome('level'); -> true
isPalindrome.js

It works by checking if the passed string is equal to itself in reverse order. This is achieved by first splitting the string into letter which gives us an array, this array is reversed, then joined back together. In terms of performance, the best way is probably using a for loop:

Copied to clipboard! Playground
const isPalindrome = str => {
    for (let i = 0; i < str.length / 2; i++) {
        if (str[i] !== str[str.length - 1 - i]) {
            return false;
        }
    }

    return true;
};
isPalindrome.js

This works by looping through the string, starting from the beginning, and checking if the character at position i, is equal to the same position, but starting from the end. If it's not, we can simply break from the loop by returning false, otherwise, we are dealing with a palindrome.

Also note that you only need to loop till the half of the string, otherwise every character would be checked twice. This is why we go till str.length / 2 in the for loop.

How to Check for Palindromes in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.