1

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?

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.