简体   繁体   中英

Not able to understand why function returning undefined

I am creating a function to remove the underscore if it is the first character of the string.

The function converts the input to uppercase and get the first character and after a validation if requires it removes the first character. Then again calling the same function with modified input to re validate. If it pass the condition I am returning the modified word from the else .But somehow it is returning undefined

 let word = '__Hello_World'; function removeFirstUnderscore(ipWord) { // converting to uppercase and getting first character; let getFirstCharacter = ipWord.toUpperCase().charCodeAt(0); // 95 // now checking if first character is in this range between 65 & 95 if (getFirstCharacter <= 65 || getFirstCharacter >= 94) { // remove the first character & again call the recursive function to revalidate let removedFirstCharWord = ipWord.split('').splice(1).join(''); console.log('**** ', removedFirstCharWord); removeFirstUnderscore(removedFirstCharWord) } else { // if first character is within range then return it return ipWord; } } console.log(removeFirstUnderscore(word))

You have an if statement.

If the condition is not met, you return ipWord .

If the condition is met, you call removeFirstUnderscore(removedFirstCharWord) but return nothing.

If you want to return the result of a recursive call, then you need to return it.

return removeFirstUnderscore(removedFirstCharWord);

您需要在if块中添加return语句。

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