2
var obj = {name: 'tim', bio: 'lol'};

var arr = [{name: 'beba', bio:'lulu'}, {name: 'keh', bio: 'kih'}];

var newArr = arr.concat([obj]);
or
var newArr = arr.concat(obj);

Both concats work but one is with square brackets and the other without them. Are they both correct?

2
  • It's not nice to use two different forms. One for adding arrays into an array and one for adding anything else. It's inconsistent and increases the risk of accidental mistakes. Commented Apr 10, 2017 at 16:03
  • .concat() is funny... it invokes a spread operator if the provided argument is an array. Sometimes nice, sometimes not so nice. Commented Apr 10, 2017 at 17:47

1 Answer 1

3

If you look at the docs of concat

Yes it is fine. concat function is flexible enough.

The concat method creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array). It does not recurse into nested array arguments.

It internally checks what you are passing and do the things.

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

Update :

var newArr = arr.concat(obj);

Means you are passing a single object to concat function.

var newArr = arr.concat([obj]);

Means you are passing an array with being a single object in it.

Basically [] denotes an array.

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

1 Comment

Thanks, I'm curious what do square brackets do in concat? We're not adding an array but an object // Ah, ok, got it. Thanks

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.