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

Unveiling the Fascination of the Collatz Conjecture: Exploring Sequence Creation with JavaScript

The Collatz Conjecture, also known as the 3x+1 problem, is a fascinating mathematical puzzle that has intrigued mathematicians for decades. It has sparked publications with titles such as The Simplest Math Problem Could Be Unsolvable, or The Simple Math Problem We Still Can’t Solve because it is, indeed, rather simple-looking.

Read more

The Art of Data Visualization: Exploring D3.js

Data is everywhere, flowing into our applications from various sources at an unprecedented rate. However, raw data alone holds little value unless it can be transformed into meaningful insights.

Read more

JavaScript’s Secret Weapon: Supercharge Your Web Apps with Web Workers

During an interview, I was asked how we could make JavaScript multi-threaded. I was stumped, and admitted I didn’t know… JavaScript is a single-threaded language.

Read more