Friday, October 24, 2025
HomeLanguagesJavascriptCollect.js whenEmpty() Function

Collect.js whenEmpty() Function

Collect.js is a fluent and convenient wrapper for working with arrays and objects. The whenEmpty() function executes the callback function when the collection is empty. 

Installation: Install the Collect.js module using the following command:

npm install --save collect.js

Syntax:  

collection.whenEmpty(callback)

Parameters: This function takes only one parameter i.e. the callback function which executes if the collection is empty.

Return Value: This function returns the new collection object.

Example 1: Filename-index.js 

Javascript




// Requiring module
const collect = require('collect.js')
 
// User defined collection
var myCollection = []
 
// Creating collection object
const collection = collect(myCollection);
 
// Callback execution since collection object is empty
collection.whenEmpty(item => item.push('Greetings'));
 
// Printing collection
console.log(collection.all());


Run the index.js file using the following command:

node index.js

Output:

[ 'Greetings' ]

Example 2: Filename-index.js 

Javascript




// Requiring module
const collect = require('collect.js')
 
// User defined collection
var myCollection = ['One', 'Two', 'Three']
 
// Creating collection object
const collection = collect(myCollection);
 
// No callback execution since collection is not empty
collection.whenEmpty((item) => {
  item.push('Four')
  item.push('Five')
  item.push('Six')
});
 
// Printing collection
console.log(collection.all());


Run the index.js file using the following command:

node index.js

Output:

[ 'One', 'Two', 'Three']

Reference: https://collect.js.org/api/whenEmpty.html

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS