Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 394
ajsie Avatar asked Dec 25 '09 17:12

ajsie


People also ask

How do you avoid adding to an array if element already exists?

To push an element in an array if it doesn't exist, use the includes() method to check if the value exists in the array, and push the element if it's not already present. The includes() method returns true if the element is contained in the array and false otherwise. Copied!

How do you know if an element doesn't exist in an array?

The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.

How do I check if an array is empty in JavaScript?

The array can be checked if it is empty by using the array. length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.

Can an array have empty elements?

To check if an array contains empty elements call the includes() method on the array, passing it undefined as a parameter. The includes method will return true if the array contains an empty element or an element that has the value of undefined .


4 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 : []
like image 80
Rich Avatar answered Oct 07 '22 14:10

Rich


var arr = arr || [];
like image 20
Brian Campbell Avatar answered Oct 07 '22 16:10

Brian Campbell


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

like image 60
mynameistechno Avatar answered Oct 07 '22 14:10

mynameistechno


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 = [];
}
like image 12
Gumbo Avatar answered Oct 07 '22 14:10

Gumbo