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

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

var arr = arr || [];

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

<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>	
	

Solution 7 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionajsieView Question on Stackoverflow
Solution 1 - JavascriptRichView Answer on Stackoverflow
Solution 2 - JavascriptBrian CampbellView Answer on Stackoverflow
Solution 3 - JavascriptmynameistechnoView Answer on Stackoverflow
Solution 4 - JavascriptGumboView Answer on Stackoverflow
Solution 5 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 6 - JavascriptM RAHMANView Answer on Stackoverflow
Solution 7 - JavascriptslebetmanView Answer on Stackoverflow