Efficiently Check Empty JavaScript Collections

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28199{{"`Efficiently Check Empty JavaScript Collections`"}} javascript/data_types -.-> lab-28199{{"`Efficiently Check Empty JavaScript Collections`"}} javascript/arith_ops -.-> lab-28199{{"`Efficiently Check Empty JavaScript Collections`"}} javascript/comp_ops -.-> lab-28199{{"`Efficiently Check Empty JavaScript Collections`"}} javascript/destr_assign -.-> lab-28199{{"`Efficiently Check Empty JavaScript Collections`"}} end

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.

Other JavaScript Tutorials you may like