16

I was browsing through some code and I was wondering how this could be useful

grid.push([].concat(row));

In my understanding it is the same as

grid.push([row]);

Why the 'concat' fuss?

1
  • 1
    Because row might be a primitive (or simply not an array) value. Commented May 27, 2016 at 7:47

4 Answers 4

20

You want to use .concat when you need to flatten the array and not have an array consisting of other arrays. E.g.

var a = [1,2,3];
var b = [4];

Scenario 1

console.log(b.push(a));
// Result: [4, [1,2,3]]

Scenario 2

console.log(b.concat(a));
// Result: [4,1,2,3]

So both of your scenarios in an array of array. Since [].concat() results in an array only, pushing both [row], [].concat(row) has the same result.

But if you want a flattened array, there is a slight change needed in your code, that you have to .concat the array row with grid and not .push the result of concat to it, as shown in scenario 2

Sign up to request clarification or add additional context in comments.

5 Comments

console.log(b.push([a]));... (grid.push([row]);). It is how OP has specified in post.. I am curious about the difference...
Both will produce array of an array...Better to provide executable snippet with valid syntax as provided in question...
By both do you mean b.concat(a) and b.push(a) or the ones referred in OPs question?
We are dealing with the code OP has provided right ? I am not concerned with the code provided in your answer..
Ok. On second glance I got what you were telling. Let me updated the answer
9

Check my variant:

let arr = [];
let tmp = [ 1, 2, '300$' ];
arr.push(...tmp);

Comments

1
var canEmptyArray = [];
grid = [...(grid), ...(canEmptyArray), ...(row)];

All arrays can be empty as long as it is in the array format

Comments

0

With grid.push([row]); you are pushing an array containing the row itself. If row is an array (e.g. [0, 1, 2]). You will push an array containing another array (i.e. [[0, 1, 2]]).

With grid.push([].concat(row));, you are pushing an array containing the elements contained in row (i.e. [0, 1, 2]).

However it is unclear why it is not just written grid.push(row) which, if row is an array, could seem more or less the same as grid.push([].concat(row));.

I can find two explanations for this:

  1. row is not an array but an "array-like" object and [].concat(row) is used to convert it (just like Array.from could do).

  2. Your coder does not want to push row but a copy of row instead that protected against any further modification of the original row.

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.