flen flen -4 years ago 34
Javascript Question

Why is my recursive JavaScript function not returning the string?

The following function returns undefined. Why?

function noReturn(arg) {
arg += " bar";
if (arg.length <= 100) noReturn(arg);
else {console.log(arg); return arg;}
}

noReturn("foo");
//logs in the console: "foo bar bar bar bar....", but returns undefined


EDIT: ouch... of course! Thank you for your answers, all of them were perfect.

Answer Source

The function doesn't return anything because you've defined it to not return anything for inputs whose length is <= 100.

function noReturn(arg) {
  arg += " bar";
  if (arg.length <= 100) noReturn(arg); 
  //                    ^---- no return statement
  else {console.log(arg); return arg;}
}

If you want the result from recursion to propagate back, you must add the return statement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download