Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Sun May 14 2023

Check if a word is a palindrome using JavaScript

In this short tutorial, we will create a function in JavaScript for checking if a word is a palindrome or not. This tutorial will be an extension of our previous guide on reversing a string.

What is a palindrome?

A palindrome is a text or number that is the same after you reverse it. So for example radar, Racecar and 2002 is all example of palindromes

Solution

Let's get our hands dirty and create our functions. We will start with creating a function for reversing the string. We will use the example from this guide.

const reverse = (str) => { if (!str) { return ""; } let reveresed = ""; let index = str.length - 1; while (index >= 0) { reveresed += str[index]; index--; } return reveresed; };

All right, so that is our function for reversing a string. And now, we will use it for our palindrome check.

const isPalindrome = (value) => { const sequence = "" + value; const reversed = reverse(sequence); return sequence.toLowerCase() === reversed.toLowerCase(); };

Notes

  • We are initializing a new string called sequense that is a string since numbers should also work, such as 2002, and our reverse() function requires a string.

  • We are transforming both string to lower case when we compare them, since Radar will be radaR otherwise and fail our check.

Testing

Let's test our function and see how it goes.

console.log(isPalindrome("racingcar")); // false console.log(isPalindrome("RadAr")); // true console.log(isPalindrome(2002)); // true console.log(isPalindrome("radar radar")); // true

All right, it passed our testing!

Outro

That's it for this guide. This type of problems are very common when you first start your journey as becomming a software developer, and they are really good to get into the problem solving mindset that is required when we face tougher problems. I hope you enjoyed this guide, and thanks for reading.

All the best,

signatureSun May 14 2023
See all our articles