Alwaysblue
Alwaysblue

Reputation: 11830

setting empty array in function argument

I was going through JS practise code (for interview) and I saw that the instructor have used/assigned empty array in function parameter

function walk(collection, result = []) {
  collection.forEach(item => {
    if(isTheItem(item)) result.push(item);
    else walk(item[0].children, result);
  });
  return result;
}

In general, is the above code and the following code equal

  function walk(collection) {
      const result = []
      collection.forEach(item => {
        if(isTheItem(item)) result.push(item);
        else walk(item[0].children, result);
      });
      return result;
    }

Even from the recursive point of view? and if not, can someone please explain me the difference?

Upvotes: 1

Views: 4656

Answers (2)

MikeB
MikeB

Reputation: 623

That syntax is basically a placeholder - if no paramater is supplied as a function argument, then an empty array is assigned by default.

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370699

is the above code and the following code equal

No, because in your second code, walk only accepts one argument, and every call of walk (whether recursive or not) will have a new result. Your second code will currently only output items from the top level in the collection.

To fix the second code, you would have to accept a second argument to pass along the result, something like:

function walk(collection, result) {
  if (!result) {
    result = [];
  }
  collection.forEach(item => {
    if(isTheItem(item)) result.push(item);
    else walk(item[0].children, result);
  });
  return result;
}

Upvotes: 2

Related Questions