Q: "TypeError: Invalid attempt to spread non-iterable instance": Adding either an Array or Object to an Array So, to add one array to another in Javascript there is:
concat()
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c']  (remains unchanged)
// y = ['d', 'e', 'f']  (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']

push.apply()
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f']  (remains unchanged)

...spreadOperator
var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = [...x, ...y];
// x = ['a', 'b', 'c']  (remains unchanged)
// y = ['d', 'e', 'f']  (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']


However, let's say that var x is an Array of Objects, and var y could either be an Array of more Objects or an Object instance...
Q.) I was wondering if there is a quick method that can handle the creation of a new Array from either two Arrays or one Array and a singular object...? I assumed the following might work:
let x = []
let y = {} OR []
let z = [...x, ...y];

When y is an Array, this is fine, but when y is an Object we would see the TypeError: Invalid attempt to spread non-iterable instance...so, are there any possible methods to avoid such a scenario?

A: As Harmandeep said, this could be an implementation:


const concat = (a,b) => [
  ...a,
  ...(Array.isArray(b) ? b : [b])
]

console.log(
  concat([{a:'a'}], [{b:'b'}]),
  concat([{a:'a'}], {b:'b'}),
)



A: 

let x = ['a', 'b']
let a = {}
let b = [{}]
console.log(x.concat(a))
console.log(x.concat(b))


It depends on what you are trying to achieve.
let x = ['a','b']
let y = {} OR [{}]
let z = ...;

If you are expecting
z = ['a','b',{}]

Array.prototype.concat can solve this.
let z = x.concat(y)

Array.prototype.concat handles arrays and non arrays and append them accordingly

A: 
are there any possible methods to avoid such a scenario?

Yes, type guards
let y: object | Array<object>  = {}
let z: Array<any> = [];

if(y instanceof Array) {
   let z = [...x, ...y];
}

