Samson Kemba
Samson Kemba

Reputation: 29

Passing arrays as function parameter using rest parameter syntax

The following function takes in multiple values as parameter for its function using the rest parameter syntax.

Both console.logs will give the correct result [1,2,3].

But shouldn't the first console.log give following result -> [[1],[2],[3]] since it is not collecting 3 numbers but 3 arrays?

function joinArrays(...vals) {
  return vals.reduce((acc, next) => acc.concat(next), []);
}

console.log(joinArrays([1], [2], [3]));
console.log(joinArrays(1, 2, 3));

Upvotes: 2

Views: 171

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370759

concat is a bit odd. It can either accept an array as an argument, in which case it will create a new array including all elements of both arrays:

console.log(
  [1, 2].concat([3, 4])
);

Or, it can accept a single element as an argument, in which case it will create a new array including that one additional element:

console.log(
  [1, 2].concat(3)
);

Here, your joinArrays([1],[2],[3]) is doing the first process, taking every item from every array and creating a new array from those items.

Upvotes: 4

Related Questions