Skip to main content Link Search Menu Expand Document (external link)

count() : Count Items in Collection


On this page

Summary

Count the number of items in a collection or array.

Signature

count(collection)

Parameters

Parameter Type Required Description
collection Array/Collection Yes The collection to count

Returns

Type: Number (Integer)

The number of items in the collection. Returns 0 for null or empty collections.


Examples

Simple Count

<p>Total items: </p>

Data:

doc.Params["model"] = new {
    items = new[] { "Apple", "Banana", "Cherry", "Date" }
};

Output:

<p>Total items: 4</p>

Summary Statistics

<h3>Order Summary</h3>
<p>Number of items: </p>
<p>Total cost: $</p>
<p>Average price: $</p>

Data:

doc.Params["model"] = new {
    orderItems = new[] {
        new { name = "Widget A", price = 10.50 },
        new { name = "Widget B", price = 15.00 },
        new { name = "Widget C", price = 8.75 }
    }
};

Output:

<h3>Order Summary</h3>
<p>Number of items: 3</p>
<p>Total cost: $34.25</p>
<p>Average price: $11.42</p>

Conditional Display Based on Count


  <p>You have  new notifications</p>

  <p>No new notifications</p>

Data:

doc.Params["model"] = new {
    notifications = new[] { "Message 1", "Message 2", "Message 3" }
};

Output:

<p>You have 3 new notifications</p>

Progress Indicator

<p>Progress:  of  tasks completed</p>

Data:

doc.Params["model"] = new {
    tasks = new[] {
        new { name = "Task 1", completed = true },
        new { name = "Task 2", completed = false },
        new { name = "Task 3", completed = true },
        new { name = "Task 4", completed = true }
    }
};

Output:

<p>Progress: 3 of 4 tasks completed</p>

Notes

  • Returns 0 for null or empty collections
  • Does not count nested collections (only top-level items)
  • Efficient O(1) operation for most collection types
  • Useful for:
    • Displaying item counts
    • Calculating averages
    • Progress tracking
    • Conditional logic based on size
    • Pagination calculations
  • For conditional counting (e.g., count items where condition is true), use countOf() instead
  • For string length, use length() function

See Also