How to create an array if an array does not exist yet?
const list = Array.isArray(x) ? x : [x];
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
Or if x
could be an array and you want to make sure it is one:
const list = [].concat(x);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
You can use the typeof
operator to test for undefined and the instanceof
operator to test if it’s an instance of Array:
if (typeof arr == "undefined" || !(arr instanceof Array)) {
var arr = [];
}
var arr = arr || [];
If you want to check whether an array x exists and create it if it doesn't, you can do
x = ( typeof x != 'undefined' && x instanceof Array ) ? x : []