Javascript Algorithms

Check if Strings are Palindromes with JavaScript

1 min read

A palindrome is a word, phrase, or sequence that reads the same backward as forward. If you’ve learned how to reverse a string (if you haven’t, we wrote an article involving it here), then a straight-forward, easy solution to this problem might come instantly to mind. You might reverse the string, compare it to the original, unchanged value, and there you have it, a solution.

This works, but let’s explore another solution. It’s always better to know multiple ways to solve something.

Directions
  • Given a string, return true if the string is a palindrome or false if it is not.
  • Palindromes are strings that form the same word if it is reversed.
Examples
  • palindrome("racecar") === true
  • palindrome("abcdefg") === false
The Solution From our Description
function palindrome(str) {
  return str.split("").reverse().join("") === str;
}
palindrome("racecar");
// Output: true

That’s it. Very simple indeed. Let’s explore another solution:

function palindrome(str) {
  return str.split("").every((char, i) => {
    return char === str[str.length - i - 1];
  });
}
palindrome("Hello");

In the above solution, we used the array .every() method, which checks whether all elements (char) pass the tests provided by the function. (You might be wondering how we’re using an array method. Remember that .split() converts a string to an array.)

The code basically says ‘for every character’, return char equal to str minus i minus 1. Here, char is the regular ordered string (i.e. 'H', 'e', 'l', 'l', 'o'), while the str - i - 1 will be the reverse (i.e. 'o', 'l', 'l', 'e', 'H'), so as you can imagine, these two values will be compared, and thus we will get our true or false value.

That’s it!

Don’t forget to check out these three simple algorithms, and let us know what you think in the Disqus comments below!

About the Author

Matt Fay

Matt Fay

Matt is the founder of JavaScript Today, a platform dedicated to high-quality JavaScript education and commentary. With a deep curiosity for technology, he gravitates toward understanding how things work and has been diving into the world of information security. Outside of coding, Matt enjoys exploring languages; he can understand some Russian and Italian, and is currently learning Thai.

Learn AI Skills with Codecademy (729x90)

Discussion (Loading...)

Join the conversation

Join the Discussion

Sign in to share your thoughts and engage with the JavaScript Today community.

Loading comments...

Related Articles

Continue your learning journey with these related posts

Never Miss a JavaScript Update

Join our community of developers and receive insightful articles and coding tips every week.