JavaScript Program to Check Palindrome String
str === str.split('').reverse().join('').Examples
How to Think About It
Algorithm
Code
function isPalindrome(str) { return str === str.split('').reverse().join(''); } console.log(isPalindrome('madam')); console.log(isPalindrome('hello')); console.log(isPalindrome('racecar'));
Dry Run
Let's trace the string 'madam' through the code
Input string
str = 'madam'
Split string into array
['m', 'a', 'd', 'a', 'm']
Reverse array
['m', 'a', 'd', 'a', 'm']
Join array back to string
'madam'
Compare original and reversed
'madam' === 'madam' => true
| Original String | Reversed String | Is Palindrome? |
|---|---|---|
| madam | madam | true |
Why This Works
Step 1: Splitting the string
We use split('') to turn the string into an array of characters so we can reverse it.
Step 2: Reversing the array
The reverse() method flips the order of characters in the array.
Step 3: Joining back to string
We use join('') to combine the reversed array back into a string for comparison.
Step 4: Comparing strings
If the original string and reversed string are exactly the same, the string is a palindrome.
Alternative Approaches
function isPalindrome(str) { let left = 0; let right = str.length - 1; while (left < right) { if (str[left] !== str[right]) return false; left++; right--; } return true; } console.log(isPalindrome('madam')); console.log(isPalindrome('hello'));
function isPalindrome(str) { let reversed = ''; for (let i = str.length - 1; i >= 0; i--) { reversed += str[i]; } return str === reversed; } console.log(isPalindrome('racecar')); console.log(isPalindrome('test'));
Complexity: O(n) time, O(n) space
Time Complexity
The program processes each character once to reverse the string, so it runs in linear time relative to string length.
Space Complexity
It uses extra space to store the reversed string, which is proportional to the input size.
Which Approach is Fastest?
The two-pointer method uses O(1) space and is faster for large strings, while the built-in reverse method is simpler but uses extra memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Built-in reverse | O(n) | O(n) | Simple and short code |
| Two-pointer comparison | O(n) | O(1) | Large strings, memory efficient |
| Manual reverse with loop | O(n) | O(n) | Clear step-by-step logic |
split, reverse, and join for concise palindrome checks.