Strange return value from recursive func

return str.concat(“ay”) is undefined, but console.log(str.concat(“ay”) is correct…

**Your code so far**
function translatePigLatin(str) {
const reg = /^[aeiou]/;
if (reg.test(str)) {
    console.log(str.concat('ay'));
    return str.concat('ay');
}
let x = str.split('');
let y = x.shift();
x.push(y);
str = x.join('');
translatePigLatin(str);
}

console.log(translatePigLatin("csonsonant"));

**Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Pig Latin

Link to the challenge:

This is not a good problem for recursion.

In any case, this part of the code doesn’t have a return value

Because you do not have return statement here:

your recursion is kinda go deeper, BUT it is one way ticket, it is making recursive calls:

function translatePigLatin(str) {
const reg = /^[aeiou]/;
if (reg.test(str)) {
    console.log('going into if with str ===', str)
    console.log("logging str.concat('ay') ", str.concat('ay'));
    console.log('checking str value before returning:  ', str)
    return str.concat('ay');
}
console.log('going lower under if block')
let x = str.split('');
let y = x.shift();
x.push(y);
str = x.join('');
console.log('and now goes new recursive call, will be passing str===', str)
translatePigLatin(str);
}

console.log(translatePigLatin("csonsonant"));

/*
going lower under if block
and now goes new recursive call, will be passing str=== sonsonantc
going lower under if block
and now goes new recursive call, will be passing str=== onsonantcs
going into if with str === onsonantcs
logging str.concat('ay')  onsonantcsay
checking str value before returning:   onsonantcs
undefined
*/

But when the base case reached - full stop, it is not passing results backwards, it just stays there on the deepest level of the tree.

So, the very first call, which is loggeed here

console.log(translatePigLatin("csonsonant"));

indeed undefined

So, to make it more clear: this undefined is simply not the result of this:

result of the above return statement is not visible in the version of code you posted.

1 Like