How do I check if a value is an empty array or object in JavaScript?
Benjamin C
benjamin c profile pic

To check if a value is an empty array or object in JavaScript, you can use the following approaches: 1. For an array: - Using thelength property: You can check if the length of the array is zero, indicating that it is empty.

1
2
3
4
5
6

     const array = [];
     if (array.length === 0) {
       // Array is empty
     }
     

- Using theArray.isArray() method: You can check if the value is an array and also has a length of zero.

1
2
3
4
5
6

     const array = [];
     if (Array.isArray(array) && array.length === 0) {
       // Array is empty
     }
     

2. For an object: - Using theObject.keys() method: You can check if the object has no own enumerable properties by checking if the length of the keys array is zero.

1
2
3
4
5
6

     const obj = {};
     if (Object.keys(obj).length === 0) {
       // Object is empty
     }
     

- Using afor...in loop: You can iterate over the object's properties and check if it has any own properties.

1
2
3
4
5
6
7
8
9
10
11
12
13

     const obj = {};
     let isEmpty = true;
     for (let key in obj) {
       if (obj.hasOwnProperty(key)) {
         isEmpty = false;
         break;
       }
     }
     if (isEmpty) {
       // Object is empty
     }
     

Note that these checks only determine if the array or object itself is empty, not if its nested elements are empty. If you also need to check for nested empty values, you would need to implement recursive checks to examine the elements within the array or object. Choose the appropriate approach based on your specific use case and the requirements of your code.