[Intermediate Algorithm Scripting - Steamroller] Change in value after it returns the value

just before returning the value in else block, the value is correct but after it returns, return value changes to undefined
My code so far

function steamrollArray(arr) {
  let newArr = [];
  let isNested = false;
  for (let i=0; i<=arr.length-1; i++) {
    if (arr[i].length == undefined || typeof arr[i] === "string" ) {
      newArr.push(arr[i])
    } else {
        if (arr[i].length > 1) {
          for (let j=0; j<=arr[i].length-1; j++) {
            if (arr[i][j].length != undefined) {
              isNested = true;
            }
            newArr.push(arr[i][j])
          }
        } else {
          if (arr[i][0].length != undefined) {
            isNested = true;
          }
            newArr.push(arr[i][0])
        }
      }
    }
    
    if (isNested) {
      steamrollArray(newArr)
    } else {
      console.log("return Value inside else block: ", newArr)
      return newArr;
    }
  }

console.log("function output: ", steamrollArray([1, [2], [3, [[4]]]]));

Output of function

return Value inside else block:  [ 1, 2, 3, 4 ]
function output:  undefined

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/116.0

Challenge: Intermediate Algorithm Scripting - Steamroller

Link to the challenge:

From else returned is newArray, but what is returned when if condition is true?

When if condition is true, it calls function steamRollArray and passes newArras argument if there is an array inside newArr.

The return Value inside else block: [ 1, 2, 3, 4 ] in console is printed only if array is not nested (or not nested anymore).

For example this will return correct result:

console.log("function output: ", steamrollArray([1, 2, 3, 4]));

When function is called recursively, something needs to be done with the result of such call. Otherwise the result of function call can be undefined, as that’s default what function returns, if it doesn’t have explicit return.

Looking at the if/else:

    console.log('before if/else', newArr);
    if (isNested) {
      steamrollArray(newArr)
    } else {
      console.log("return Value inside else block: ", newArr)
      return newArr;
    }
    console.log('after if/else', newArr);  // if this is printed, then at some point, function returns undefined

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