How to create an array if an array does not exist yet?

Viewed 101960

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

7 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 : []

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 : [];
<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>   

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 = [];
}
Related