Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The program should output the result

Many thanks!

>Solution :

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')
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading