[javascript] How to write palindrome in JavaScript

I wonder how to write palindrome in javascript, where I input different words and program shows if word is palindrome or not. For example word noon is palindrome, while bad is not.

Thank you in advance.

This question is related to javascript palindrome

The answer is


function palindrome(str) {
    var lenMinusOne = str.length - 1;
    var halfLen = Math.floor(str.length / 2);

    for (var i = 0; i < halfLen; ++i) {
        if (str[i] != str[lenMinusOne - i]) {
            return false;
        }
    }
    return true;
}

Optimized for half string parsing and for constant value variables.


Alternative solution for using Array.prototype.every()

function palindrome(str) {
  return str.split('').every((char, index) => {
     return char === str[str.length - index - 1];
  });
}

Here's a one-liner without using String.reverse,

const isPal = str => Array
  .apply(null, new Array(strLen = str.length))
  .reduce((acc, s, i) => acc + str[strLen - (i + 1)], '') === str;

Use something like this

function isPalindrome(s) {
    return s == s.split("").reverse().join("") ? true : false;
}

alert(isPalindrome("noon"));

alternatively the above code can be optimized as [updated after rightfold's comment]

function isPalindrome(s) {
    return s == s.split("").reverse().join("");
}

alert(isPalindrome("malayalam")); 
alert(isPalindrome("english")); 

Look at this:

function isPalindrome(word){
    if(word==null || word.length==0){
        // up to you if you want true or false here, don't comment saying you 
        // would put true, I put this check here because of 
        // the following i < Math.ceil(word.length/2) && i< word.length
        return false;
    }
    var lastIndex=Math.ceil(word.length/2);
    for (var i = 0; i < lastIndex  && i< word.length; i++) {
        if (word[i] != word[word.length-1-i]) {
            return false;
        }
     }
     return true;
} 

Edit: now half operation of comparison are performed since I iterate only up to half word to compare it with the last part of the word. Faster for large data!!!

Since the string is an array of char no need to use charAt functions!!!

Reference: http://wiki.answers.com/Q/Javascript_code_for_palindrome


How can I verify if a number is palindrome?

I have my function but is not right because it's for a string not a number:

function palindrom(str){
  for(var i=0;i<str.length;i++){
    if(str[i]!==str[str.length-i-1]){
      return false;
    }
  }
  return true;
}

console.log(palindrom("121"));
console.log(palindrom("1234321"));
console.log(palindrom("3211432"));

This function will remove all non-alphanumeric characters (punctuation, spaces, and symbols) and turn everything lower case in order to check for palindromes.

function palindrome(str){

    var re = /[^A-Za-z0-9]/g;
    str = str.toLowerCase().replace(re, '');
    return str == str.split('').reverse().join('') ? true : false;

}

Faster Way:

-Compute half the way in loop.

-Store length of the word in a variable instead of calculating every time.

EDIT: Store word length/2 in a temporary variable as not to calculate every time in the loop as pointed out by (mvw) .

function isPalindrome(word){
   var i,wLength = word.length-1,wLengthToCompare = wLength/2;

   for (i = 0; i <= wLengthToCompare ; i++) {
     if (word.charAt(i) != word.charAt(wLength-i)) {
        return false;
     }
   }
   return true;
} 

You can try the following code with n/2 complexity

   palindrom(word)
   {
        let len = word.length

        let limit = len % 2 ? (len - 1)/2 : (len/2)

        for(let i=0; i < limit; i++)
        {
            if(word[i] != word[len-i-1])
            {
                alert('non a palindrom')
                return
            }
        }

        alert('palindrom')
        return;
   }

calling the function

palindrom('abba')


Best Way to check string is palindrome with more criteria like case and special characters...

function checkPalindrom(str) {
    var str = str.replace(/[^a-zA-Z0-9]+/gi, '').toLowerCase();
    return str == str.split('').reverse().join('');
}

You can test it with following words and strings and gives you more specific result.
1. bob
2. Doc, note, I dissent. A fast never prevents a fatness. I diet on cod

For strings it ignores special characters and convert string to lower case.


I think this implementation covers pretty much every case. I hope it's useful to someone:

function isPalindrome(word){
    if(typeof word === 'undefined' || word === null){
        console.log("argument is undefined");
        return;
    }

    if(typeof word === 'string'){

       word = word.replace(/\s/gi,"");

     if(word.length < 1){
        console.log("wrong argument");
        return;
      }

      if(word.length === 1){
        console.log("It's palindrome!");
        return;
      }

      for(var i=0;i<Math.floor(word.length/2);i++){

        if(word[i] !== word[word.length - 1 - i]){
          console.log("It's not palindrome");
          return;
        }
      }
      console.log("It's palindrome");

    }else{

       console.log("argument must be a string");

    }

}

And then you can try with these cases:

isPalindrome("nurses run");
isPalindrome("abcdcba");
isPalindrome("hello world");
isPalindrome("  ");
isPalindrome(" ");
isPalindrome("");
isPalindrome(null);
isPalindrome();
isPalindrome(100);
isPalindrome({"name":"John"});

Frist I valid this word with converting lowercase and removing whitespace and then compare with reverse word within parameter word.

function isPalindrome(input) {
    const toValid = input.trim("").toLowerCase();
    const reverseWord = toValid.split("").reverse().join("");
    return reverseWord == input.toLowerCase().trim() ? true : false;
}
isPalindrome("    madam ");
//true

A simple one line code to check whether the string is palindrome or not:

_x000D_
_x000D_
function palindrome (str) {_x000D_
_x000D_
  return str === str.split("").reverse().join("");_x000D_
_x000D_
}
_x000D_
<!-- Change the argument to check for other strings -->_x000D_
<button type="button" onclick="alert(palindrome('naman'));">Click Me<utton>
_x000D_
_x000D_
_x000D_

The above function will return true if the string is palindrome. Else, it will return false.


This tests each end of the string going outside in, returning false as soon as a lack of symmetry is detected. For words with an odd number of letters, the center letter is not tested.

function isPalindrome(word){
    var head = 0;
    var tail = word.length - 1;

    while (head < tail) {
        if (word.charAt(head) !== word.charAt(tail)){
            return false
        } else {
            head ++;
            tail --;
        }
    };
    return true;
};

The most important thing to do when solving a Technical Test is Don't use shortcut methods -- they want to see how you think algorithmically! Not your use of methods.

Here is one that I came up with (45 minutes after I blew the test). There are a couple optimizations to make though. When writing any algorithm, its best to assume false and alter the logic if its looking to be true.

isPalindrome():

Basically, to make this run in O(N) (linear) complexity you want to have 2 iterators whose vectors point towards each other. Meaning, one iterator that starts at the beginning and one that starts at the end, each traveling inward. You could have the iterators traverse the whole array and use a condition to break/return once they meet in the middle, but it may save some work to only give each iterator a half-length by default.

for loops seem to force the use of more checks, so I used while loops - which I'm less comfortable with.

Here's the code:

/**
 * TODO: If func counts out, let it return 0
 *  * Assume !isPalindrome (invert logic)
 */
function isPalindrome(S){
    var s = S
      , len = s.length
      , mid = len/2;
      , i = 0, j = len-1;

    while(i<mid){
        var l = s.charAt(i);
        while(j>=mid){
            var r = s.charAt(j);
            if(l === r){
                console.log('@while *', i, l, '...', j, r);
                --j;
                break;
            }
            console.log('@while !', i, l, '...', j, r);
            return 0;
        }
        ++i;
    }
    return 1;
}

var nooe = solution('neveroddoreven');  // even char length
var kayak = solution('kayak');  // odd char length
var kayaks = solution('kayaks');

console.log('@isPalindrome', nooe, kayak, kayaks);

Notice that if the loops count out, it returns true. All the logic should be inverted so that it by default returns false. I also used one short cut method String.prototype.charAt(n), but I felt OK with this as every language natively supports this method.


All these loops! How about some functional goodness :) May run in to tail call issues on old/current js engines, solved in ES6

function isPalendrome(str){
    var valid = false;
    if(str.length < 2 ) return true;
    function even(i,ii){
        str[i]===str[ii] ? ((i+1 !== ii) ? even(i+1,ii-1) : valid = true) : null
    }
    function odd(i, ii){
        str[i]===str[ii] ? ((i !== ii) ? odd(i+1,ii-1) : valid = true) : null
    }
    if(str.length % 2){
        return odd(0,str.length-1),valid;
    }else{
        return even(0,str.length-1),valid;
    }
}

To test your call stack run this code, you will be able to parse strings double the call stack size

function checkStackSize(){
    var runs = 70000;
    var max_process = 1;
    var max = 0;
    function recurse_me() {
        max_process++;
        if(max_process === runs) return;
        max = max_process;
        try {
            recurse_me()
        } catch(e) {
            max =  max_process;
        }
    }
    recurse_me()
    console.log(max);
}

Due to the symmetrical nature of the problem you could chunk the string from the outside in and process the chunks that are within call stack limits.

by that I mean if the palindromes length is 1000. You could join 0-250 and 750-1000 and join 250-499 with 500-749. You can then pass each chunk in to the function. The advantage to this is you could run the process in parallel using web workers or threads for very large data sets.


Or you could do it like this.

var palindrome = word => word == word.split('').reverse().join('')

Here's another way of doing it:

function isPalin(str) {
  str = str.replace(/\W/g,'').toLowerCase();
  return(str==str.split('').reverse().join(''));
}

Here is an optimal and robust solution for checking string palindrome using ES6 features.

_x000D_
_x000D_
const str="madam"_x000D_
var result=[...str].reduceRight((c,v)=>((c+v)))==str?"Palindrome":"Not Palindrome";_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


I think following function with time complexity of o(log n) will be better.

    function palindrom(s){
    s = s.toString();
    var f = true; l = s.length/2, len = s.length -1;
    for(var i=0; i < l; i++){
            if(s[i] != s[len - i]){
                    f = false; 
                    break;
            }
    }
    return f;

    }

console.log(palindrom(12321));


Let us start from the recursive definition of a palindrome:

  1. The empty string '' is a palindrome
  2. The string consisting of the character c, thus 'c', is a palindrome
  3. If the string s is a palindrome, then the string 'c' + s + 'c' for some character c is a palindrome

This definition can be coded straight into JavaScript:

function isPalindrome(s) {
  var len = s.length;
  // definition clauses 1. and 2.
  if (len < 2) {
    return true;
  }
  // note: len >= 2
  // definition clause 3.
  if (s[0] != s[len - 1]) {
    return false;
  }
  // note: string is of form s = 'a' + t + 'a'
  // note: s.length >= 2 implies t.length >= 0
  var t = s.substr(1, len - 2);
  return isPalindrome(t);
}

Here is some additional test code for MongoDB's mongo JavaScript shell, in a web browser with debugger replace print() with console.log()

function test(s) {
  print('isPalindrome(' + s + '): ' + isPalindrome(s));
}

test('');
test('a');
test('ab');
test('aa');
test('aab');
test('aba');
test('aaa');
test('abaa');
test('neilarmstronggnortsmralien');
test('neilarmstrongxgnortsmralien');
test('neilarmstrongxsortsmralien');

I got this output:

$ mongo palindrome.js
MongoDB shell version: 2.4.8
connecting to: test
isPalindrome(): true
isPalindrome(a): true
isPalindrome(ab): false
isPalindrome(aa): true
isPalindrome(aab): false
isPalindrome(aba): true
isPalindrome(aaa): true
isPalindrome(abaa): false
isPalindrome(neilarmstronggnortsmralien): true
isPalindrome(neilarmstrongxgnortsmralien): true
isPalindrome(neilarmstrongxsortsmralien): false

An iterative solution is:

function isPalindrome(s) {
  var len = s.length;
  if (len < 2) {
    return true;
  }
  var i = 0;
  var j = len - 1;
  while (i < j) {
    if (s[i] != s[j]) {
      return false;
    }
    i += 1;
    j -= 1;
  }
  return true;
}

ES6 way of doing it. Notice that I take advantage of the array method reduceRight to reverse a string (you can use array methods on strings if you give the string as context, as low level - strings are arrays of chars). No it is not as performant as other solutions, but didn't see any answer that came it it using es6 or higher order functions so figured I'd throw this one out there.

const palindrome = str => {
  const middle = str.length/2;
  const left = str.slice(0, middle)
  const right = Array.prototype.reduceRight.call(str.slice(Math.round(middle)), (str, char) => str + char, '')
  return left === right;
}

To avoid errors with special characters use this function below

function palindrome(str){
  var removeChar = str.replace(/[^A-Z0-9]/ig, "").toLowerCase();
  var checkPalindrome = removeChar.split('').reverse().join('');
  if(removeChar === checkPalindrome){
     return true;
  }else{
    return false;
  }
}

Taking a stab at this. Kind of hard to measure performance, though.

function palin(word) {
    var i = 0,
        len = word.length - 1,
        max = word.length / 2 | 0;

    while (i < max) {
        if (word.charCodeAt(i) !== word.charCodeAt(len - i)) {
            return false;
        }
        i += 1;
    }
    return true;
}

My thinking is to use charCodeAt() instead charAt() with the hope that allocating a Number instead of a String will have better perf because Strings are variable length and might be more complex to allocate. Also, only iterating halfway through (as noted by sai) because that's all that's required. Also, if the length is odd (ex: 'aba'), the middle character is always ok.


What i use:-

function isPalindrome(arg){
    for(let i=0;i<arg.length;i++){
        if(arg[i]!==arg[(arg.length-1)-i]) 
          return false;
    return true;
}}

function palindrome(str) {    
    var testString = str.toLowerCase();


    var expression = /[a-z0-9\^s]/gi;
    if (testString.match(expression).reverse().join("") == testString.match(expression).join("")) {
        return true;
    } else {
        return false;
    }
}

function palindrome(s) {
  var re = /[\W_]/g;
  var lowRegStr = s.toLowerCase().replace(re, '');
  var reverseStr = lowRegStr.split('').reverse().join(''); 
  return reverseStr === lowRegStr;
}

function Palindrome(str) {
  let forwardStr = str.toLowerCase().replace(/[\W_]/g, '');
  let reversedStr = forwardStr.split('').reverse().join();

  return forwardStr === reversedStr;
}
console.log(Palindrome('madam'));

str1 is the original string with deleted non-alphanumeric characters and spaces and str2 is the original string reversed.

function palindrome(str) {

  var str1 = str.toLowerCase().replace(/\s/g, '').replace(
    /[^a-zA-Z 0-9]/gi, "");

  var str2 = str.toLowerCase().replace(/\s/g, '').replace(
    /[^a-zA-Z 0-9]/gi, "").split("").reverse().join("");


  if (str1 === str2) {
    return true;
  }
  return false;
}

palindrome("almostomla");

function isPalindrome(word) {
    let strLen = word.length;
    word = word.toLocaleLowerCase();

    if (strLen === 0 || strLen === 1) {
        return true;
    }

    if (word[0] === word[strLen - 1])  {
        return isPalindrome(word.slice(1, strLen - 1) );
    }  

    return false;
}

function isPalindrome(s) {
    return s == reverseString(s);
}

console.log((isPalindrome("abcba")));

function reverseString(str){
    let finalStr=""
    for(let i=str.length-1;i>=0;i--){
        finalStr += str[i]
    }
    return finalStr
}

Below code tells how to get a string from textBox and tell you whether it is a palindrome are not & displays your answer in another textbox

<html>
<head>
<meta charset="UTF-8"/>
<link rel="stylesheet" href=""/>

</head>  
<body>   
<h1>1234</h1>
<div id="demo">Example</div>
<a  accessKey="x" href="http://www.google.com" id="com" >GooGle</a>
<h1 id="tar">"This is a Example Text..."</h1>
Number1 : <input type="text" name="txtname" id="numb"/>
Number2 : <input type="text" name="txtname2" id="numb2"/>
Number2 : <input type="text" name="txtname3" id="numb3" />
<button type="submit"  id="sum" onclick="myfun()" >count</button>
<button type="button"  id="so2" onclick="div()" >counnt</button><br/><br/>
<ol>
<li>water</li>
<li>Mazaa</li>
</ol><br/><br/>
<button onclick="myfun()">TryMe</button>
    <script>
    function myfun(){
    var pass = document.getElementById("numb").value;
    var rev = pass.split("").reverse().join("");
    var text = document.getElementById("numb3");
    text.value = rev;
    if(pass === rev){
    alert(pass + " is a Palindrome");
    }else{
    alert(pass + " is Not a Palindrome")
    }
    }
    </script>
</body>  
</html>  

My short solution, with the length of 66 characters. The result: true or false.

_x000D_
_x000D_
function isPalindrome(s) {_x000D_
  s=s.toLowerCase().match(/\w/g);_x000D_
  return s.join()==s.reverse().join();_x000D_
}
_x000D_
_x000D_
_x000D_


Note: This is case sensitive

function palindrome(word)
{
    for(var i=0;i<word.length/2;i++)
        if(word.charAt(i)!=word.charAt(word.length-(i+1)))
            return word+" is Not a Palindrome";
    return word+" is Palindrome";
}

Here is the fiddle: http://jsfiddle.net/eJx4v/


function palindrome(str){
    for (var i = 0; i <= str.length; i++){ 
        if  (str[i] !== str[str.length - 1 - i]) {
            return "The string is not a palindrome";
        }
    }
return "The string IS a palindrome"
}

palindrome("abcdcba"); //"The string IS a palindrome"
palindrome("abcdcb"); //"The string is not a palindrome";

If you console.log this line: console.log(str[i] + " and " + str[str.length - 1 - i]), before the if statement, you'll see what (str[str.length - 1 - i]) is. I think this is the most confusing part but you'll get it easily when you check it out on your console.


/* Following function does the below mentioned task.

 1. Fetch all the substrings of a given string. 
 2. Find which of the substrings are palindromes.
 3. Find the longest palindrome.
 4. Find if the longest palindrome is a lucky palindrome.

  */

function SubstringMnipulations(S) {
    let Str = S.toString(); 
    let AllSubStrs = splitSubstrings(Str);
    let Pelindromes = arePelindrome(AllSubStrs);
    let LongestPelindrome = getLongestString(Pelindromes);
    let isPrimeVar = isPrime(LongestPelindrome);
    return {
      "possibleSubstrings": AllSubStrs,
      "pelindromes": Pelindromes,
      "longestPelindrome": LongestPelindrome,
      "isLuckyPelindrome": isPrimeVar
    };
  }

function splitSubstrings(Str) {
  let StrLength = Str.length;
  let maxIndex = StrLength;
  let AllSubStrs = [];
  for(var index = 0; index < maxIndex; index++ ) {
    for(var innerIndex = 1; innerIndex <= maxIndex-index; innerIndex++) {
      AllSubStrs.push(Str.substring(index, (index+innerIndex)));
    }
  }
  return AllSubStrs;
}

function arePelindrome(StrArr) {
  let pelindrome = [];
  for(i=0; i<StrArr.length;i++) {
    if(isPelindrome(StrArr[i])) {
      if(StrArr[i].length>1) {
        pelindrome.push(StrArr[i]);
      }
    }
  }

  return pelindrome;
}

function isPelindrome(Str) {
  let strLen = Str.length;
  let firstHalfIndex = 0;
  if(strLen==1) {
    return true;
  }

  let firstHalf = "";
  let secondHalf = "";

  if(strLen>1 && strLen%2==0) {
    firstHalfIndex = strLen/2;
    firstHalf = Str.substring(0, firstHalfIndex);
    secondHalf = Str.substring((firstHalfIndex), strLen);
  } else {
    firstHalfIndex = (strLen-1)/2;
    firstHalf = Str.substring(0, firstHalfIndex);
    secondHalf = Str.substring((1+firstHalfIndex), strLen);
  }

  secondHalf = reverseString(secondHalf);
  return firstHalf === secondHalf;
}

function reverseString(Str) {
  return Str.split("").reverse().join("");
}

function getLongestString(Str) {
  let lengthCount = [];
  for(i=0; i<Str.length;i++) {
    lengthCount.push(Str[i].length);
  }

  return Str[lengthCount.indexOf(Math.max(...lengthCount))];
}

function isPrime(Str) {
  let input = Str.length;
  let prime = true;
    for (let i = 2; i <= Math.sqrt(input); i++) {
        if (input % i == 0) {
            prime = false;
            break;
        }
    }
    return prime && (input > 1);
}

The code is concise quick fast and understandable.

TL;DR

Explanation :

Here isPalindrome function accepts a str parameter which is typeof string.

  1. If the length of the str param is less than or equal to one it simply returns "false".
  2. If the above case is false then it moves on to the second if statement and checks that if the character at 0 position of the string is same as character at the last place. It does an inequality test between the both.

    str.charAt(0)  // gives us the value of character in string at position 0
    str.slice(-1)  // gives us the value of last character in the string.
    

If the inequality result is true then it goes ahead and returns false.

  1. If result from the previous statement is false then it recursively calls the isPalindrome(str) function over and over again until the final result.

_x000D_
_x000D_
 function isPalindrome(str){_x000D_
 _x000D_
 if (str.length <= 1) return true;_x000D_
 if (str.charAt(0) != str.slice(-1)) return false;_x000D_
 return isPalindrome(str.substring(1,str.length-1));_x000D_
 };_x000D_
_x000D_
_x000D_
document.getElementById('submit').addEventListener('click',function(){_x000D_
 var str = prompt('whats the string?');_x000D_
 alert(isPalindrome(str))_x000D_
});_x000D_
_x000D_
document.getElementById('ispdrm').onsubmit = function(){alert(isPalindrome(document.getElementById('inputTxt').value));_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<form id='ispdrm'><input type="text" id="inputTxt"></form>_x000D_
_x000D_
<button id="submit">Click me</button>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


function isPalindrome(str) {
  var isPalindrome = true;

  if(str.length === 2){
    return isPalindrome;
  }
  for(let i = 0, d = str.length - 1; i<(d-i); i++ )
  {
    if(str[i] !== str[d - i] ){
      return !isPalindrome
    }
  }
   return isPalindrome
  }

_x000D_
_x000D_
function palindrome(str) {_x000D_
  var re = /[\W_]/g; // or var re = /[^A-Za-z0-9]/g;_x000D_
  var lowRegStr = str.toLowerCase().replace(re, '');_x000D_
  var reverseStr = lowRegStr.split('').reverse().join('');_x000D_
  return reverseStr === lowRegStr;_x000D_
}_x000D_
console.log(palindrome("A nut for a jar of tuna"));_x000D_
console.log(palindrome("Helo World"));
_x000D_
_x000D_
_x000D_


I am not sure how this JSPerf check the code performance. I just tried to reverse the string & check the values. Please comment about the Pros & Cons of this method.

function palindrome(str) {
    var re = str.split(''),
        reArr = re.slice(0).reverse();

    for (a = 0; a < re.length; a++) {
        if (re[a] == reArr[a]) {
            return false;
        } else {
            return true;
        }
    }
}

JS Perf test


    function palindrome(str) {
        var re = /[^A-Za-z0-9]/g;
        str = str.toLowerCase().replace(re, '');
        var len = str.length;
        for (var i = 0; i < len/2; i++) {
            if (str[i] !== str[len - 1 - i]) {
                return false;
            }
        }
        return true;
    }

Try this:

var isPalindrome = function (string) {
    if (string == string.split('').reverse().join('')) {
        alert(string + ' is palindrome.');
    }
    else {
        alert(string + ' is not palindrome.');
    }
}

document.getElementById('form_id').onsubmit = function() {
   isPalindrome(document.getElementById('your_input').value);
}

So this script alerts the result, is it palindrome or not. You need to change the your_id with your input id and form_id with your form id to get this work.

Demo!


Try this

isPalindrome = (string) => {
    if (string === string.split('').reverse().join('')) {
        console.log('is palindrome');
    }
    else {
        console.log('is not palindrome');
    }
}

isPalindrome(string)

How about this one?

function pall (word) {

    var lowerCWord = word.toLowerCase();
    var rev = lowerCWord.split('').reverse().join('');

    return rev.startsWith(lowerCWord);
    }

pall('Madam');

You could also do something like this :

function isPalindrome(str) {
var newStr = '';

for(var i = str.length - 1; i >=0; i--) {
    newStr += str[i];
}

if(newStr == str) {
    return true;
    return newStr;
} else {
    return false;
    return newStr;
}
}

_x000D_
_x000D_
    function reversName(name){_x000D_
            return name_x000D_
                  .split('')_x000D_
                  .reverse()_x000D_
                  .join('') === name ;_x000D_
    };_x000D_
    console.log(reversName('suus'));_x000D_
    console.log(reversName('suusss'));
_x000D_
_x000D_
_x000D_


Here is a 1 line program to check if your string is a palindrome :-

((s) => `Is ${s} a palindrome ? \n Answer is :- ${s.split('').reverse().join('') == s}`)('bob')

Just modify the last parameter of this IIFE to check different inputs. This is perhaps the best solution.


25x faster + recursive + non-branching + terse

function isPalindrome(s,i) {
 return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
}

See my complete explanation here.


For better performance you can also use this one

function palindrome(str) {
 str = str.split("");
 var i = str.length;
 var check = "Yes"
 if (i > 1) {
    for (var j = 0; j < i / 2; j++) {
        if (str[j] != str[i - 1 - j]) {
            check = "NO";
            break;
           }
        }
        console.log(check);
    } else {
    console.log("YES");
  }
}