Steamroller - returning a 'if...else' statement

Tell us what’s happening:
Hello FCC!
I am still not 100% sure how return works in an if…else statement, so I am trying to get a workaround going, however, when I console.log the result of the ‘else’ statement the answer is correct BUT when I try to pass it to another variable to return it, the answer is ‘undefined’.

Your code so far


function steamrollArray(arr) {
  let flat = [].concat(...arr);
  var final;
    if (flat.some(Array.isArray)) {
    steamrollArray(flat) 
  } else {
    console.log(flat)
// returns correct answer: [1,2,3,4]
    final = flat;
  }
  return final
// returns undefined]
}





steamrollArray([1, [2], [3, [[4]]]]);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller

In this case it’s a bit hard to grasp the return statement since you are creating a recursive function.

In JS, unless you specify what value a function should return, it will return undefined by default.

In this case, since you are recursively add functions call to the stack, the “undefined” will override the “return”.
I like to imagine it like documents onto an office desk:

1 - first iteration -> calls itself (since Array is Array) -> add a new “document paper” onto itself. -> no explicit return
2 - second iteration -> call itself (since Array is Array) -> add a new “document paper” onto itself. -> no explicit return
3 - third iteration -> now the if condition is false.

Now the program (the office employee) will have 3 documents piled to its desk. Will start reviewing them in the order they are piled: 3 to 1.

He looks at the last one and see that it return [1,2,3,4], but then under it it still have two documents, that both return undefined, so when they pile back the undefined is the last value.

All you have to do is simply “link” them by be explicit and return the result of the previous call stack.


tl:dr return all the way up to the stack:

if (flat.some(Array.isArray)) {
    return steamrollArray(flat) 
  }

Hope it helps :+1:

1 Like