JavaScript Algorithm | Palindrome
Ok, now a palindrome refers to a word that is the same when spelled either way. for example, the word “MOM” which spelled from left to right or right to left is always “MOM”, Which tell us mom is always mom ( tears in my eyes 😛 ).
Now for the solution, we will write a function and pass the string to be tested as an argument to the function, and then loop on it in reverse order and then store each looped character in a variable. once loop completes.
We then compare the string which is passed as the argument and the reversed string we created for, Equality and return truthy or falsy.
There are several solutions to write this algorithm like for example, we can also split the given string argument which results in an array and then reverse the array and use the join() method on the array items which results in a string which then be compared for equality with the passed argument.
function palindrome(str){
let strReversed = '';
for (var i = str.length-1; i >= 0; i--) {
strReversed += str[i];
}
return strReversed == str ;
}
palindrome('mom');