views:

304

answers:

5

how do i check if a specific array exists, and if not it will be created?

+2  A: 

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
You could use alse instanceof operator.
el.pescado
To my eye, this is easier to read than Rich's version.
DOK
I've just become totally obsessed with the "? :" ternary operator as I've been working on code that has large expressions everywhere.
Rich
A: 

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
Sorry, bad answer. See Gumbo's answer for better code.
slebetman
+4  A: 
var arr = arr || [];
Brian Campbell
But this doesn’t check if *arr* is an array.
Gumbo
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
If `arr` is already defined in the relevant scope, then why bother with `var ...`? You can just do `arr = arr || [];`
J-P
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
+8  A: 

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
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.
J-P
That is true. How would one handle that case?
Rich
@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.
CMS
Oh, that's quite clever!
Rich
+2  A: 

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 : [];
CMS
Need to declare `arr`
kangax
@kangax Declaration isn't necessary in this context.
Justin Johnson
@Justin Johnson How so?
kangax
The declaration is necessary, but I thought it was pretty obvious that if `arr` is undeclared a `ReferenceError` will be thrown in the right-hand side of the assignment...
CMS