DSA Questions: checkPalindrome

Niani Byrd
2 min readSep 29, 2021

--

Given the string, check if it is a palindrome.

Let’s continue our JS Data Structures and Algorithms series by talking about palindromes. What’s a palindrome? These are words that are the same forward and backward. Like madam, civic, or radar. How can we write a function that checks whether or not two strings or palindromes of each other? Or, in the words: the reverse of each other?

The easiest way to solve this is by using the .reverse method. But there’s a catch….the .reverse method can only be used on arrays not strings. So first we must convert our string into an array. Create a variable…lets call it pal. And we’ll call the split method to turn out string into an array that’s divided at the space. Chain the method with reverse which will reverse the order of the array, and then call .join to rejoin the array back into a string. That sounds complicated but let’s see what that looks like:

function checkPalindrome(inputString) {    let pal = inputString.split('').reverse().join('')}

On the next line, we use a simple if/else statement to see if our variable pal is equal to the argument. If it is, we return true. If not, return false.

function checkPalindrome(inputString) {     let pal = inputString.split('').reverse().join('')         if (pal === inputString) {            return true          }     return false}

There you have it! The key to solving this problem is understanding that in order to use the reverse method, we must convert the string into an array. Don’t forget to convert it back into a string as the question calls for you to compare strings and not arrays! Happy Coding!

--

--

Responses (1)