Home > front end >  Palindrome Check in javascript but with while loop
Palindrome Check in javascript but with while loop

Time:12-22

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!

CodePudding user response:

Here's how you can fix these issues and correctly check whether a 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 = true

while (i < word.length) {
  if(word[i] != reverse[i]) {
    isPalindrome = false
    break;
  }
  i  
}

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

CodePudding user response:

Alternative: pick off letters of the word and its copy from both sides until they either don't match (no palindrome) or all are matched (is palindrome):

const isPalindrome = word => {
  const letters = word.toLowerCase().split("");
  // copy letters
  const checkWord = [...letters];
  
  while (letters.length) {
    if (letters.shift() !== checkWord.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`)}`);

  • Related