Help me to understand why the code is not working as I expect

Hello campers,

I would appreciate if anyone can explain to me why this code’s output is undefined:

function checker(value) {
  
  if (Array.isArray(value)) {
    value.forEach(insideVal => {
      return checker(insideVal);
    });
    
  }
  else return value;
  
}

console.log(checker([1,2,3])); // -> undefined

while this one is OK:

function checker(value) {
  
  if (Array.isArray(value)) {
    value.forEach(insideVal => checker(insideVal));
    
  }
  else return value;
  
}

console.log(checker(1)); // -> 1

In the first case I expected to see something like

1
2
3

Any help will be appreciateed! :slight_smile:

Hello!

Neither of them will do what You need :sweat_smile:. Of course, the second one seems to work because You’re passing a single value, but when You iterate the array with forEach, the callback doesn’t return a value, hence the result will be undefined.

What You would need to do is accept a callback function and call it for every single value (that’s not an array).