Introduction
In this lab, we will explore a common programming problem of checking if a collection or object is empty in JavaScript. We will use a simple function to determine if the provided value is an empty object/collection, has no enumerable properties, or is any type that is not considered a collection. This lab will help you understand how to efficiently check for empty objects or collections in your JavaScript code.
Checking if a Collection is Empty
To check if a collection is empty, you can open the Terminal/SSH and type node. This program checks if a value is an empty object/collection, has no enumerable properties, or is any type that is not considered a collection.
To use the program, check if the provided value is null or if its length is equal to 0. Here's an example code:
const isEmpty = (val) => val == null || !(Object.keys(val) || val).length;
You can then test the program using the following codes:
isEmpty([]); // true
isEmpty({}); // true
isEmpty(""); // true
isEmpty([1, 2]); // false
isEmpty({ a: 1, b: 2 }); // false
isEmpty("text"); // false
isEmpty(123); // true - type is not considered a collection
isEmpty(true); // true - type is not considered a collection
Summary
Congratulations! You have completed the Collection Is Empty lab. You can practice more labs in LabEx to improve your skills.