Palindrome
Challenge Description
Check if a given string is a palindrome. A palindrome reads the same backward as forward. For example:
- "abba" is a palindrome.
- "cddc" is a palindrome.
Tips to Solve
tip
- Convert the string to an array using the
split
method. - Reverse the array using the
reverse
method. - Convert the array back to a string using the
join
method. - Compare the original string with the reversed string.
Step-by-Step Solution
Let's break down the solution into easy steps:
-
Convert the String to an Array: Use the
split
method to convert the string into an array of characters.const strArray = "abba".split(""); // ["a", "b", "b", "a"]
-
Reverse the Array: Use the
reverse
method to reverse the order of the elements in the array.const reversedArray = strArray.reverse(); // ["a", "b", "b", "a"]
-
Convert the Array Back to a String: Use the
join
method to combine the elements of the array back into a string.const reversedString = reversedArray.join(""); // "abba"
-
Compare the Strings: Compare the original string with the reversed string to check if they are the same.
const isPalindrome = "abba" === reversedString; // true
Full Solution Code
Here is the complete solution using the steps above:
const palindrome = (str) => str.split("").reverse().join("") === str;
console.log(palindrome("abba")); // Output: true
console.log(palindrome("cddc")); // Output: true
console.log(palindrome("hello")); // Output: false