DEV Community

Ben
Ben

Posted on

Code Challenges pt. 2

Part 1 of this series is Reverse a String.

Next up, we're working with Palindromes

Prompt:
You are given a string. Check to see if it is a palindrome. If it is return true, if it is not return false.

Include all characters (spaces, punctuation, numbers, etc.) in determining if the string is a palindrome.

Note: Palindromes are words that are the same when spelled forwards as backwards, e.g. racecar.

Example outcomes:
isPalindrome('racecar') === true
isPalindrome('animal') === false
isPalindrome('mom') === true

Code:
Note: all we're doing is checking to see if the string is the same forwards as backwards...

function isPalindrome(string){
    const reversed = string.split('').reverse().join('')
    return reversed === string
}
Enter fullscreen mode Exit fullscreen mode

Why does this work?

First we just make a reversed copy of the string.

We could use the for-loop version (Version 2 of Reverse a String), but it's not the only thing we're doing so we might as well just use the built-in methods.

From there, since all we're doing is comparing the string being passed in to the reversed copy, we return the boolean value from the expression reversed === string.

Top comments (0)