Open In App

Palindrome in JavaScript

We will understand how to check whether a given value is a palindrome or not in JavaScript. A palindrome is a value that reads the same from backward or forward.

To perform this check we will use the following approaches:



Approach 1: Using for loop (efficient approach)

Example: This example implements the above approach.






function isPalindrome(str) {
    let j = str.length - 1
    for (let i = 0; i < str.length / 2; i++) {
        if (str[i] != str[j]) {
            return false;
        }
        j--;
    }
    return true;
}
 
let str1 = "racecar";
let str2 = "nitin";
let str3 = "Rama";
 
console.log(isPalindrome(str1));
console.log(isPalindrome(str2));
console.log(isPalindrome(str3));

Output
true
true
false

Approach 2: Using for loop-II

Example: This example implements the above approach.




function isPalindrome(str) {
    let rev = "";
    for (let i = str.length - 1; i >= 0; i--) {
        rev += str[i];
    }
    if (rev == str) {
        return true
    } else {
        return false;
    }
}
 
let str1 = "racecar";
let str2 = "nitin";
let str3 = "Rama";
 
console.log(isPalindrome(str1));
console.log(isPalindrome(str2));
console.log(isPalindrome(str3));

Output
true
true
false

Approach 3: Using split(), reverse() and join() methods

Example: This example implements the above approach on string




function isPalindrome(str) {
    let rev = str.split("").reverse().join("");
 
    if (rev == str) {
        return true
    }
    return false
 
}
 
let str1 = "racecar";
let str2 = "nitin";
let str3 = "Rama";
 
console.log(isPalindrome(str1));
console.log(isPalindrome(str2));
console.log(isPalindrome(str3));

Output
true
true
false

To know more about How to check whether a passed string is palindrome or not in JavaScript?


Article Tags :