Search code examples
javascriptfunctionrecursionreturnreturn-value

two function with same functionality return different value because i haven't use "return" keyword inside one function exact before function call


I wrote a function that flatten and array.


  const multiArray = [1, [2, 3, [4, [5]]], 6, [7, 8, 9, [10]]]

  let newArray = []
  const flatenArray = (params) => {
    params.map((sm) => {
      if(Array.isArray(sm)) {
        return flatenArray(sm)
      }
      newArray.push(sm);
    })
    return newArray
  }

  //console.log(flatenArray(multiArray)) result [1,2,3,4,5,6,7,8,9,10]

The above function works fine.

but if I remove the return keyword from the "if" block then does it returns something else?

let newArray2 = []
  const flatenArray2 = (params) => {
    params.map((sm) => {
      if(Array.isArray(sm)) {
        flatenArray(sm)
      }
      newArray2.push(sm);
    })
    return newArray2
  }

  console.log(flatenArray2(multiArray)) 
  //result [1,[2,3,[4,[5]]],6,[7,8,9,[10]]]

Now I would like to know...

Why should I use the return keyword there even when I'm calling it?

What is happening when I use the return keyword there?


Solution

  • What is happening when I use the return keyword there?

    The function (the callback that you're passing to map) does return a value and stop executing. This means it will not reach the next line, newArray.push(sm);, after the if statement, which does push the sm array onto the result array in your second implementation.

    Why should I use the return keyword there even when I'm calling it?

    You shouldn't actually. Using an else statement would be much cleaner (and also you shouldn't abuse map):

    const flattenArray = (params) => {
      for (const sm of params) {
        if (Array.isArray(sm)) {
          flattenArray(sm)
        } else {
          newArray.push(sm);
        }
      }
      return newArray
    }