How do I create an array if it does not exist yet? In other words how to default a variable to an empty array?
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!
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.
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.
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 .
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 : []
var arr = arr || [];
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
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With