How do I create an array if it does not exist yet? In other words how to default a variable to an empty array?
8 Answers
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 : []
6 Comments
Array constructor - this might occur when scripting across frames.Array.isArray(x): stackoverflow.com/a/38670091/271442if (Array.isArray(array) && array.length) You can find more here stackoverflow.com/a/24403771/364951var arr = arr || [];
5 Comments
arr is already defined in the relevant scope, then why bother with var ...? You can just do arr = arr || [];var be hoisted and therefore it'd always just become []? Edit: nvm, I am wrong :Dconst 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
2 Comments
x is not defined in both casesx is the variable that could be an array or not. You define that. This is just example code ...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 = [];
}
If you want to check if the object is already an Array, to avoid the well known issues of the instanceof operator when working in multi-framed DOM environments, you could use the Object.prototype.toString method:
arr = Object.prototype.toString.call(arr) == "[object Array]" ? arr : [];
2 Comments
arr is undeclared a ReferenceError will be thrown in the right-hand side of the assignment...