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

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


Solution 1:

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

Solution 2:

var arr = arr || [];