Vermillion Orange
Vermillion Orange

Reputation: 91

Palindrome Check in javascript but with while loop

I am trying to make a palindrome checker with the condition of having to use a while loop. It's giving me a right headache! it returns isPalindrome as false every time even if the word is a palindrome.

let word = prompt('Please Enter a word')
let reverse = word.split('').reverse().join('').toLowerCase();
i = 0
final = word.length
let isPalindrome = false

while (i < word.length) {
  if(word[i] == reverse[i])
  i++

  if(i = word.length)
  break;

  else if (i !== word.length)
  break;
}

if (i == word.length) {
  isPalindrome == true
}

else if (true) {
  isPalindrome == false
}

if (isPalindrome == true) {
  window.alert('Your word is a palindrome')
}

else if (isPalindrome == false) {
  window.alert('Your word is not a palindrome')
}

I have tried messing around with the == signs and changing the break; it used to return as always palindrome, but now it always returns as not a palindrome

The idea is to compare the word with the reverse version of it and check every index to see if it matches. If they all match the word is a palindrome (racecar && racecar) If they do not match it is not (racer && recar)

The program should output the result

Many thanks!

Upvotes: 0

Views: 925

Answers (1)

KooiInc
KooiInc

Reputation: 122956

Alternative: nibble off letters of the word from both sides and compare them until either there's one letter left (is palindrome) or they don't match (no palindrome):

const isPalindrome = word => {
  const letters = word.toLowerCase().split("");
  
  while (letters.length > 1) {
    if (letters.shift() !== letters.pop()) {
      // not a palindrome: break the loop
      // by returning false
      return false;
    };
  }
  return true;
}

console.log(`racecar ${isPalindrome(`racecar`)}`);
console.log(`rotator ${isPalindrome(`rotator`)}`);
console.log(`carrace ${isPalindrome(`carrace`)}`);
console.log(`rotonda ${isPalindrome(`rotonda`)}`);

Upvotes: 1

Related Questions