You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array does not exist or is empty
}
Update
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ⇒ do not attempt to process array
}
To break it down:
Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values likenull,undefinedand anything else that is not an array.
Note that this will also eliminate array-like objects, such as theargumentsobject and DOMNodeListobjects. Depending on your situation, this might not be the behavior you're after.The
array.lengthcondition checks whether the variable'slengthproperty evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons likearray.length != 0orarray.length !== 0are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}
Answer from Robby Cornelissen on Stack Overflowthis is my situation
let matches : string[] | null = topic.match(this._DEVICE_TOPIC_REGEXP);
console.log("handleNewMeasure, topic", topic, "matches", matches);
if (typeof matches === undefined ) {
return;
}
let device_id = matches[1];
I cannot go on because last line warns me that it could be empty
I have an array in a function and I want the function to return true/false depending on if the array is empty (return true if not empty and vice versa)
I have narrowed down the condition to these 2 possible return statements. Which one is preferred?
return result.recordset.length == 0 return !!result.recordset.length
Suppose I have these types
interface Person {
name: string;
age?: number;
}
type People = Person[];I then want to use the array type like so
const people: People = []; const firstPerson = people[0]; console.log(firstPerson.name);
TypeScript doesn't complain about this usage because it doesn't have a clue about the size of arrays at compile time (I'm assuming) and thus it sees "sure, an array of Person, the first element must be a Person and not undefined, seems legit". Obviously though, when the JS is executed, this will fail with the error Cannot read property "name" of undefined.
I've come up with a rudimentary type guard, but that feels a bit cumbersome to use everywhere and doesn't catch everything:
const arePeople = (array: People): array is People => {
return Array.isArray(array) && array.length > 0 && array[0].name != null
}So the question is, is there a way to tell TypeScript that an array has at least 1 item of the correct type, other than using that typeguard
if (typeof image_array !== 'undefined' && image_array.length > 0) {
// the array is defined and has at least one element
}
Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var whenever declaring a variable:
<?php echo "var image_array = ".json_encode($images);?>
// add var ^^^ here
And then make sure you never accidently redeclare that variable later:
else {
...
image_array = []; // no var here
}
To check if an array is either empty or not
A modern way, ES5+:
if (Array.isArray(array) && array.length) {
// array exists and is not empty
}
An old-school way:
typeof array != "undefined"
&& array != null
&& array.length != null
&& array.length > 0
A compact way:
if (typeof array != "undefined" && array != null && array.length != null && array.length > 0) {
// array exists and is not empty
}
A CoffeeScript way:
if array?.length > 0
Why?
Case Undefined
Undefined variable is a variable that you haven't assigned anything to it yet.
let array = new Array(); // "array" !== "array"
typeof array == "undefined"; // => true
Case Null
Generally speaking, null is state of lacking a value. For example a variable is null when you missed or failed to retrieve some data.
array = searchData(); // can't find anything
array == null; // => true
Case Not an Array
Javascript has a dynamic type system. This means we can't guarantee what type of object a variable holds. There is a chance that we're not talking to an instance of Array.
supposedToBeArray = new SomeObject();
typeof supposedToBeArray.length; // => "undefined"
array = new Array();
typeof array.length; // => "number"
Case Empty Array
Now since we tested all other possibilities, we're talking to an instance of Array. In order to make sure it's not empty, we ask about number of elements it's holding, and making sure it has more than zero elements.
firstArray = [];
firstArray.length > 0; // => false
secondArray = [1,2,3];
secondArray.length > 0; // => true
The array is a reference type. When you would like to check it with [ ], they aren't equal. They're different; checking this condition with length is better. So, based on your code, you should do something like this :
if (!testArray || testArray.length == 0 || testArray.includes(value)) {
// do something
}
function isValueInArrayOrEmpty(updated) {
console.log(Boolean(updated instanceof Array && (updated.length == 0 || (updated.length > 0 && updated.includes(value)))));
}
let value = "hello";
let updated = [];
isValueInArrayOrEmpty(updated);
let updated2 = "hello";
isValueInArrayOrEmpty(updated2);
let updated3 = Object;
isValueInArrayOrEmpty(updated3);
let updated4 = [Object];
isValueInArrayOrEmpty(updated4);
let updated5 = ["hello"];
isValueInArrayOrEmpty(updated5);
let updated6 = ["not hello"];
isValueInArrayOrEmpty(updated6);
VM815:2 true
VM815:2 false
VM815:2 false
VM815:2 false
VM815:2 true
VM815:2 false