There are various methods to verify whether an array is empty or undefined in JavaScript.
1. Using if Statement
The simplest method to check if an array is empty or undefined is by using a basic if
statement. You can test the array’s existence and its length.
let arr; if (!arr || arr.length === 0) { console.log("Array is empty or does not exist"); } else { console.log("Array exists and is not empty"); }
2. Using Optional Chaining (?.)
Optional chaining (?.
) allows you to check the existence of an array before accessing its properties, such as length
.
let arr; if (arr?.length === 0) { console.log("Array is empty"); } else if (!arr) { console.log("Array does not exist"); } else { console.log("Array exists and is not empty"); }
3. Combining Logical Operators
Logical operators like ||
and &&
can simplify checks for undefined and empty arrays.
let arr; if (!(arr && arr.length)) { console.log("Array is empty or does not exist"); } else { console.log("Array exists and is not empty"); }
4. Using Array.isArray() Method
The Array.isArray()
method explicitly checks if a variable is an array.
let arr; if (!Array.isArray(arr) || arr.length === 0) { console.log("Array is empty or does not exist"); } else { console.log("Array exists and is not empty"); }
5. Using Ternary Operator
The ternary operator (? :
) is a concise way to perform checks and execute actions based on the result.
let arr; console.log( !arr ? "Array does not exist" : arr.length === 0 ? "Array is empty" : "Array exists and is not empty" );
6. Using try…catch for Safety
In cases where you’re unsure if the variable is an array or if it might cause runtime errors, try...catch
can safeguard your code.
let arr; try { if (!arr || arr.length === 0) { console.log("Array is empty or does not exist"); } else { console.log("Array exists and is not empty"); } } catch (error) { console.log("An error occurred:", error.message); }