Search code examples
javascriptpalindrome

Assistance with javascript palindrome


I am trying to solve a palindrome using a for loop in JavaScript (my code is below).

I cannot figure out what I am doing wrong. If someone can please correct and explain, it will be much appreciated. I am fairly new to coding.

var word = window.prompt("Enter a word");
function palindrome(a) {
  var reversed = '';
  for (i = 0; i <= a.length; i++) {
    reversed = reversed + a[a.length - 1 - i];
  }
  if (a == reversed) {
    return "true";
  } else {
    return "false";
  }
}
document.write(palindrome(word));

Solution

  • your loop:

    for (i = 0; i <= a.length; i++) {
        reversed = reversed + a[a.length - 1 - i];
      }
    

    you just need remove -1 and start the loop with 1 because when you reached the end of the iteration you will have the length of the word -1 and this will try to access a negative position.

    after changing:

     for (let i = 1; i <= a.length; i++) {
           // you can use reversed += a[a.length - i] instead of;
           reversed = reversed + a[a.length - i];   
         }
    

    You can also reverse a string using the reverse method like this:

     reversed = a.split('').reverse().join(''); 
    

    Finally if you want to validata sentences you need to remove blank spaces and convert it in lower or upper case(usually converted in lowercase) because compare is case sensitive ("Party trap" != "part ytraP").