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!
>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')
}