简体   繁体   中英

Why does javascript 'if statements' return undefined?

This is more of a 'why does this happen' question than a trouble shooting question.

I am trying to create a function that tests whether a word is a palindrome. I thought initially that I can use an if statement it compare the word and when it is reversed. However the if statement gave me undefined. When I compared it regularly (word === reverseWord), it came back with a truth or false. My question is what is going on in the if statement for it do wonk out? Thanks!

const palindromes = function(word) {
    *//Turn word into an array*
    var arrWord = Array.from(word);
    *//Reverse the array*
    var reversedWord = arrWord.reverse();

    *//This is true*
    return arrWord === reversedWord;

    //But this is undefined?
    if (arrWord === reversedWord) {true} else {false};
}

Its returning undefined because you are not using return keyword anywhere.

Another mistake you are making is that you are comparing two arrays which reference same object in memory it arrWord === reversedWord will always return true .

Convert word to array using split('') and reverse() it. And then join('') . And finally compare reversed string and word

 const palindromes = function(word) { var reversedWord = word.split('').reverse().join(''); console.log(word === reversedWord); if (word === reversedWord) { return true } else { return false }; } console.log(palindromes("aba")) console.log(palindromes("ba"))

The code can be reduced to a single line.

 const palindromes = (word) => word.split('').reverse().join('') === word console.log(palindromes("aba")) console.log(palindromes("ba"))

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