JavaScript Program to Check Palindrome Number
num.toString() === num.toString().split('').reverse().join('').Examples
How to Think About It
Algorithm
Code
function isPalindromeNumber(num) { const str = num.toString(); const reversed = str.split('').reverse().join(''); return str === reversed; } console.log(isPalindromeNumber(121)); // true console.log(isPalindromeNumber(123)); // false console.log(isPalindromeNumber(0)); // true
Dry Run
Let's trace the number 121 through the code to see how it checks for palindrome.
Convert number to string
num = 121, str = '121'
Reverse the string
str = '121', reversed = '121'
Compare original and reversed
'121' === '121' is true
Return result
Function returns true
| num | str | reversed | isPalindrome |
|---|---|---|---|
| 121 | '121' | '121' | true |
Why This Works
Step 1: Convert number to string
We use toString() to treat the number like text so we can reverse it easily.
Step 2: Reverse the string
Splitting the string into characters, reversing the array, and joining back creates the reversed version.
Step 3: Compare original and reversed
If the reversed string matches the original, the number reads the same forwards and backwards.
Alternative Approaches
function isPalindromeNumber(num) { let original = num; let reversed = 0; while (num > 0) { reversed = reversed * 10 + num % 10; num = Math.floor(num / 10); } return original === reversed; } console.log(isPalindromeNumber(121)); // true console.log(isPalindromeNumber(123)); // false
function isPalindromeNumber(num) { const str = num.toString(); function check(s, start, end) { if (start >= end) return true; if (s[start] !== s[end]) return false; return check(s, start + 1, end - 1); } return check(str, 0, str.length - 1); } console.log(isPalindromeNumber(121)); // true console.log(isPalindromeNumber(123)); // false
Complexity: O(n) time, O(n) space
Time Complexity
The time depends on the number of digits n because we convert to string and reverse it, which takes O(n) time.
Space Complexity
Extra space is used to store the string and its reversed version, so space is O(n).
Which Approach is Fastest?
The mathematical reversal avoids string operations and uses O(1) space, making it faster and more memory efficient for large numbers.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String reversal | O(n) | O(n) | Simplicity and readability |
| Mathematical reversal | O(n) | O(1) | Performance and memory efficiency |
| Recursive string check | O(n) | O(n) | Learning recursion and elegant code |