Steamroller difference between these codes?

Steamroller difference between these codes?
0

#1

Hi!

could somebody explain me what is the difference between these codes? I tried the long one first but it was not working, so I used the arrow functions I saw online to flatten nested arrays and worked. But I don’t understand the difference.

This was the attempt

function steamrollArray(arr) {

 return arr.reduce(function(acc, val){
   if(Array.isArray(val)){
    acc.concat(steamrollArray(val))
  } else {
    acc.concat(val);
  }
  },[]);
}

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

This is the one that worked

function steamrollArray(arr) {
  return arr.reduce((acc,val) => Array.isArray(val)? acc.concat(steamrollArray(val)):acc.concat(val),[]);

}

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

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

edit: I think it is because inside the if statement, those arguments are not accessible from there, so acc is undefined as well as val. If that is the case, how can I turn them accesible? I tried using “this” but I think I am doing something wrong.


#2

functions need to return values, your first one returns nothing from the callback