Check if Strings are Palindromes with JavaScript

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!

comments powered by Disqus

Related Posts

The Great JavaScript Debate: To Semicolon or Not?

Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.

Read more

Hacktoberfest 2024: Get a Free JavaScript Today Sticker

October is here, and that means one thing in the tech world—Hacktoberfest! This annual event, powered by DigitalOcean, Cloudflare, Quira, and other sponsors, encourages developers of all skill levels to contribute to open-source projects.

Read more

Creating a Real Time Chat Application with React, Node, and TailwindCSS

In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.

Read more