82

How do I create an array if it does not exist yet? In other words how to default a variable to an empty array?

Dharman
  • 30,962
  • 25
  • 85
  • 135
ajsie
  • 77,632
  • 106
  • 276
  • 381

7 Answers7

93

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 : []
Rich
  • 3,095
  • 17
  • 17
  • 2
    This works in most cases, but it won't cover you if you plan on checking an array instantiated from a different global `Array` constructor - this might occur when scripting across frames. – James Dec 25 '09 at 18:17
  • 1
    That is true. How would one handle that case? – Rich Dec 25 '09 at 19:23
  • 2
    @Rich: See my answer here: http://stackoverflow.com/questions/1961528/javascript-check-if-array-exist-if-not-create-it/1961653#1961653, it will behave correctly on multi-framed DOM environments. – Christian C. Salvadó Dec 25 '09 at 21:32
  • 11
    The correct way to do it nowadays is to use `Array.isArray(x)`: http://stackoverflow.com/a/38670091/271442 – mynameistechno Jul 30 '16 at 04:33
  • It doesn't work when it is **null**. So a complete check would be `if (Array.isArray(array) && array.length)` You can find more here https://stackoverflow.com/a/24403771/364951 – Claudiu Oct 18 '17 at 19:29
  • That is not correct. `Array.isArray(null)` will be `false`. Your check is verifying it's a non-empty array. – mynameistechno Mar 05 '20 at 21:18
71
var arr = arr || [];
Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
  • 19
    But this doesn’t check if *arr* is an array. – Gumbo Dec 25 '09 at 17:23
  • 9
    You're right. It wasn't clear from the question if checking that it was an array in advance is necessary, or just checking to see if the variable is already defined. This is a common idiom, and is shorter and simpler than the other ones posted, so I figured I'd post it and let the questioner decide if it's sufficient. – Brian Campbell Dec 25 '09 at 17:47
  • 3
    If `arr` is already defined in the relevant scope, then why bother with `var ...`? You can just do `arr = arr || [];` – James Dec 25 '09 at 18:15
  • 4
    The question was to check whether the array already exists, and create it if not. Thus, you don't know if it's already defined. This idiom is useful if you have several files to be linked together, and don't know which one of them will be loaded first to define some global variable that they will all share. – Brian Campbell Dec 25 '09 at 18:24
  • @BrianCampbell I might be wrong but unless that's being run in global scope, wouldn't `var` be hoisted and therefore it'd always just become `[]`? Edit: nvm, I am wrong :D – whitfin Aug 26 '15 at 03:49
66
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

mynameistechno
  • 3,526
  • 1
  • 37
  • 32
12

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 = [];
}
Gumbo
  • 643,351
  • 109
  • 780
  • 844
9

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 : [];
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
0
<script type="text/javascript">

array1  = new Array('apple','mango','banana');
var storearray1 =array1;

if (window[storearray1] && window[storearray1] instanceof Array) {
    alert("exist!");
} else {
    alert('not find: storearray1 = ' + typeof storearray1)
    }

</script>   
M RAHMAN
  • 21
  • 1
-7

If you are talking about a browser environment then all global variables are members of the window object. So to check:

if (window.somearray !== undefined) {
    somearray = [];
}
slebetman
  • 109,858
  • 19
  • 140
  • 171