Why [array].concat() and [array].concat.apply() gives different output ?

That's because:

console.log( [].concat.apply([2],[[99],5,6,[2,3]]) );

is equivalent to:

console.log( [2].concat([99], 5, 6, [2,3]) );

.concat takes the multiple arguments, and merges all the arrays (and non-array arguments) into a single array. Basically, the array arguments get unpacked 1 level.

To get that output, you would have to wrap each of the array elements in an additional array.

console.log( [].concat.apply([2],[[[99]],5,6,[[2,3]]]) );

Perhaps you would prefer to use a .push based approach.

var a = [2];
a.push.apply(a, [[99],5,6,[2,3]]);
console.log(a);


Your assuming about in a way without seeing the document. See, the actual syntax for concat is,

Array.prototype.concat ( [ item1 [ , item2 [ , … ] ] ] )

So your code is barely equals to,

[].concat.apply([itm1], [itm2,itm3,itm4]...)

From your code's point of view, your code is similar to,

[2].concat([99],5,6,[2,3]);

let's dismantle your code,

console.log([].concat.apply([2],[[99],5,6,[2,3]]));
// 1. apply will call the function by applying the parameter supplied as an array.
// 2. so the first parameter for apply would be this for that function
// 3. and the second parameter for it would be the arguments in an array form.
// 4. Hence internally apply will call the function concat as,
//    [2].concat([99],5,6,[2,3]); //[2] will be 'this'

But for your requirement, you don't need to go with apply, you can use call.

console.log([].concat.call([2],[[99],5,6,[2,3]]));
//[2,[99],5,6,[2,3]]

Tags:

Javascript