简体   繁体   中英

Why does this Function written in JS return true even if the condition is not satisfied?

I am just starting to learn Javascript and one of our first assignments were the classic check_if_palindrome function. I don't understand what is wrong with my code.

 function palindrome(str1) { console.log(str1.split('').reverse().join('')); console.log(str1); if (str1 == str1.split().reverse().join('')) { return (true) } else { return (false) } } if (palindrome('wow442421') == true) { console.log('YES') } else { console.log('NOPE'); } 

You are missing the '' in the second split() . Do not repeat code, it is error prone, you should use a variable to hold the result and reuse it when necessary:

 function palindrome(str1) { const reversed = str1.split('').reverse().join(''); console.log(str1, reversed); if (str1 === reversed){ return true } else { return false } } if (palindrome('wow442421') === true) { console.log('YES') } else{ console.log('NOPE'); } 

Also, since str1 === str1.split('').reverse().join('') already returns a boolean, simply return this value, the if/else statement is not necessary:

 function palindrome(str) { return str.split('').reverse().join('') === str; } if (palindrome('wow442421')) { console.log('YES') } else{ console.log('NOPE'); } 

And if you want to make it more succinct, you can do this:

 const isPalindrome = str => str === [...str].reverse().join('') console.log(isPalindrome('wow44')); console.log(isPalindrome('Roma amoR')); 

You should use split('') instead of split() , split() will split at every space character, split('') splits at every character, which is what you want:

 function palindrome(str1) { if (str1 == str1.split('').reverse().join('')) { return true; } else { return false; } } if (palindrome('wow442421') == true) { console.log('YES') } else { console.log('NOPE'); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM