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

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

The Importance of Staying Active as a Software Developer

In today’s fast-paced digital world, developers often find themselves glued to their screens for extended periods. While this dedication is commendable, it comes with its own set of challenges.

Read more

JavaScript DOM Mastery: Top Interview Questions Explained

Mastering the Document Object Model (DOM) is crucial for any JavaScript developer. While many developers rely heavily on front-end frameworks, the underlying DOM concepts are still important.

Read more