Friday, September 19, 2025
HomeLanguagesJavascriptCollect.js | when() Function

Collect.js | when() Function

The when() function is used to callback if the first argument in the given proves to be true. In JavaScript, the array is first converted to a collection and then the function is applied to the collection.
Syntax: 

data.when(conditional ,rule)

Parameters: This function accept two parameters as mentioned above and described below:

  • rule:  This parameter holds the operation rule or the condition to be applied on the collection. 
  • conditional:  This parameter holds the conditional value true or false.  
     

Return value :  Return the modified collection list.
 

Below examples illustrate the when() function in collect.js:
Example 1: Here in this example, we take a collection and then using the when() function modify the collection.

Javascript




// It is used to import collect.js library   
const collect = require('collect.js');
  
const collection = collect([0 , 1 , 2]);
collection.when(true, items => items.push(3));
  
console.log(collection.all());


Output: 

[0 , 1 , 2 , 3]

Example 2: Same as above example but applying a different operation to perform.

Javascript




// It is used to import collect.js library   
const collect = require('collect.js');
  
const collection = collect([0 , 1 , 2]);
collection.when(true, items => items.put('Jason'));
  
console.log(collection.all());


Output: 

[ 0, 1, 2, Jason: undefined ]

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

RELATED ARTICLES

Most Popular

Dominic
32302 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6666 POSTS0 COMMENTS
Nicole Veronica
11841 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11898 POSTS0 COMMENTS
Shaida Kate Naidoo
6781 POSTS0 COMMENTS
Ted Musemwa
7056 POSTS0 COMMENTS
Thapelo Manthata
6739 POSTS0 COMMENTS
Umr Jansen
6745 POSTS0 COMMENTS