Why is the outcome undefined, what is wrong with the code?

function counter(i) {
  console.log(i)
    if (i < 10) {
  return counter(i + 1);
  } 
  return;
 }
 console.log(counter(0));

As is always the case with coding - because that’s what you’re telling it to do.

Try something like this and see if it helps you understand:

function counter(i) {
  console.log(i, 'entering counter')
  if (i < 3) {
    console.log(i, 'i < 3, making recursive call')
    const val = counter(i + 1)
    console.log(i, 'back from recursive call, returning', val)
    return val;
  }
  console.log(i, 'base case reached, returning nothing')
  return;
}

console.log(counter(0));

Good coders are good detectives.

1 Like

@kevinSmith
I am extremely grateful for your prompt help Kevin. Tech industry grows and prospers because of people like you. Thank you once again. Please suggest some online material that helps me understand the process of debugging.

You can google it, but a big part of it is just figuring it out, being a detective. Learning about browser dev tools is important too - there are amazing tools in there that beginners don’t use enough.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.