A palindrome is a string or number that reads the same forwards and backwards — "madam", "racecar", and 121 are all palindromes. Checking for one is a direct application of reversing a string: reverse the input and compare it to the original.
Check Palindrome String in JavaScript
function isPalindrome(str) {
// Normalize: lowercase and strip anything that isn't a letter or digit
const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, "");
const reversed = cleaned.split("").reverse().join("");
return cleaned === reversed;
}
console.log(isPalindrome("Madam"));
console.log(isPalindrome("Hello"));
console.log(isPalindrome("A man a plan a canal Panama"));
Output:
true
false
true
Normalizing the string first — lowercasing it and removing spaces/punctuation with a regular expression — is what lets a phrase like "A man a plan a canal Panama" register as a palindrome. Skip that step and it would fail, since the raw string has spaces and mixed case that don't mirror each other.
Check Palindrome Number in JavaScript
Numbers don't have string methods directly, so the usual approach is to convert the number to a string first, reuse the same reverse-and-compare logic, then convert back if you need a numeric result.
function isPalindromeNumber(num) {
const str = num.toString();
const reversed = str.split("").reverse().join("");
return str === reversed;
}
console.log(isPalindromeNumber(121));
console.log(isPalindromeNumber(123));
Output:
true
false
Negative numbers are a common edge case worth testing: (-121).toString() is "-121", whose reverse is "121-" — so this function correctly reports negative numbers as non-palindromes, since the minus sign breaks the symmetry.
