A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Examples include “madam,” “racecar,” and “level.” To check if a given string is a palindrome or not, you can use a simple loop that compares the first and last characters, second and second-to-last characters, and so on, until the middle of the string is reached. If all the comparisons are true, then the string is a palindrome.

Here is an example of a function that checks if a given string is a palindrome in JavaScript:

function isPalindrome(str) {
    var len = str.length;
    var mid = Math.floor(len/2);
    for ( var i = 0; i < mid; i++ ) {
        if (str[i] !== str[len - 1 - i]) {
            return false;
        }
    }
    return true;
}
console.log(isPalindrome("madam")); // Output: true
console.log(isPalindrome("hello")); // Output: false

You can also use .split('').reverse().join('') for the same operation to check for a palindrome.

Check If A Number Is A Palindrome In JavaScript

To check if a number is a palindrome in JavaScript, you can convert the number to a string, then use the same method as checking a string palindrome. Here is an example:

function isPalindrome(num) {
    var numString = num.toString();
    var len = numString.length;
    var mid = Math.floor(len/2);
    for ( var i = 0; i < mid; i++ ) {
        if (numString[i] !== numString[len - 1 - i]) {
            return false;
        }
    }
    return true;
}
console.log(isPalindrome(121)); // Output: true
console.log(isPalindrome(123)); // Output: false

Alternatively, you can also revert the number and compare it with the original number, here is an example:

function isPalindrome(num) {
  var originalNum = num;
  var reversedNum = 0;
  while (num > 0) {
    reversedNum = reversedNum * 10 + num % 10;
    num = Math.floor(num / 10);
  }
  return originalNum === reversedNum;
}
console.log(isPalindrome(121)); // Output: true
console.log(isPalindrome(123)); // Output: false

In this example, the function first initializes a variable originalNum to store the original number, then it uses a while loop to reverse the digits of the number, and it stores the reversed number in reversedNum. Finally, it compares the original number and the reversed number, and returns true if they are equal, false otherwise.

Also Read:

Categorized in: