Explore JavaScript where() Function | Collect.js Library

Since manipulating an array is a common task especially when you are dealing with a list of objects or primitive values, filtering arrays, then it’s where the where() function of JavaScript comes in.

In this article, we will aim to learn what is where() function is, along with its basic syntax, use cases, and practical examples on how to utilize it.

What is JavaScript where Function?

The where function in Collect.js is a method that allows you to filter a collection based on specific criteria.

Collect.js is a JavaScript library that enhances the functionality of working with arrays and collections, making it more convenient and expressive.

Additionally, where function is used to create a new collection that contains only the elements that meet the specified conditions.

Syntax of the where() Function

The basic syntax of the where() function is as follows:

const filteredArray = collect(collection).where(key, value);

  • collection: The array you want to filter.
  • key: The property you want to match.
  • value: The value you want to match for the given property.

How to Use the JavaScript where Function

The where() function in Collect.js is used to filter a collection based on specific conditions. It allows you to create a new collection containing only the items that meet the specified criteria.

Here’s how you can use the where() function from the Collect.js library:

  1. Install Collect.js: If you haven’t already, you need to install the Collect.js library. You can do this using npm or yarn:
   npm install collect.js
   # or
   yarn add collect.js

  1. Import Collect.js: Import the Collect.js library at the beginning of your JavaScript file:
   const collect = require('collect.js');

  1. Create a Collection: Create a collection by passing an array to the collect() function:
   const collection = collect([
     { id: 1, name: 'Alice', age: 28 },
     { id: 2, name: 'Bob', age: 32 },
     { id: 3, name: 'Eve', age: 25 }
   ]);

  1. Use the where() Function: The where() function takes three arguments: the key you want to filter on, the operator for the comparison, and the value to compare against.
   const filteredCollection = collection.where('age', '>', 28);

This will create a new collection containing items where the ‘age’ is greater than 28.

  1. Access the Filtered Items: You can use the .all() method to retrieve the filtered items as an array:
   console.log(filteredCollection.all());
   // Output:
   // [
   //   { id: 2, name: 'Bob', age: 32 }
   // ]

  1. Chaining Conditions: You can chain multiple where() conditions to filter by multiple criteria:
   const filteredCollection = collection
     .where('age', '>', 25)
     .where('name', 'like', 'A');

This will create a new collection containing items where the ‘age’ is greater than 25 and the ‘name’ includes the letter ‘A’.

The where() function is just one of the many useful functions provided by Collect.js for working with collections in a fluent and convenient manner.

It allows you to create more expressive and readable code when dealing with filtering and querying collections. Remember to refer to the official Collect.js documentation for a complete list of available methods and their usage: Collect.js Documentation

Applying the where Function: Practical Examples

Here are some practical examples of using the where() function from the Collect.js library to filter collections based on specific conditions:

Example 1: Filtering Employees

Suppose you have a collection of employee data and you want to filter out employees who are managers.

const collect = require('collect.js');

const employees = collect([
  { id: 1, name: 'Alice', isManager: false },
  { id: 2, name: 'Bob', isManager: true },
  { id: 3, name: 'Eve', isManager: false },
]);

const managers = employees.where('isManager', true);

console.log(managers.all());
// Output:
// [
//   { id: 2, name: 'Bob', isManager: true }
// ]

Example 2: Filtering Products

Let’s say you have a collection of products and you want to find products with a price greater than $50.

const products = collect([
  { id: 1, name: 'Laptop', price: 800 },
  { id: 2, name: 'Phone', price: 500 },
  { id: 3, name: 'Tablet', price: 300 },
]);

const expensiveProducts = products.where('price', '>', 50);

console.log(expensiveProducts.all());
// Output:
// [
//   { id: 1, name: 'Laptop', price: 800 },
//   { id: 2, name: 'Phone', price: 500 }
// ]

Example 3: Chaining Conditions
You can chain multiple conditions together using the where() function.

const tasks = collect([
  { id: 1, title: 'Buy groceries', isCompleted: false, priority: 'high' },
  { id: 2, title: 'Write report', isCompleted: true, priority: 'medium' },
  { id: 3, title: 'Exercise', isCompleted: false, priority: 'low' },
]);

const highPriorityIncompleteTasks = tasks
  .where('isCompleted', false)
  .where('priority', 'high');

console.log(highPriorityIncompleteTasks.all());
// Output:
// [
//   { id: 1, title: 'Buy groceries', isCompleted: false, priority: 'high' }
// ]

Remember that Collect.js provides a fluent interface, allowing you to chain methods together for more complex queries and transformations. These examples showcase how you can use the where() function to filter collections based on specific conditions.

Conclusion

In conclusion, the Collect.js where() function significantly simplifies the process of array filtering in JavaScript.

Its intuitive syntax, versatility, and performance make it a valuable tool for developers working with arrays of various types.

Whether you’re filtering objects or primitive values, where() streamlines the process and boosts your productivity.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Glay Eliver


Programmer & Technical Writer at PIES IT Solution

Glay Eliver is a programmer and writer at PIES IT Solution, author of over 600 tutorials at itsourcecode.com. Specializes in JavaScript tutorials, Microsoft Office how-tos (Excel, Word, PowerPoint), and Python error debugging covering ImportError, TypeError, AttributeError, ModuleNotFoundError, and JavaScript ReferenceError. Authored several of the site’s highest-traffic Excel and MS Office reference articles.

Expertise: JavaScript · MS Excel · MS Word · MS PowerPoint · Python · Python ImportError · Python TypeError · Python AttributeError · ModuleNotFoundError · JavaScript ReferenceError · Pygame
 · View all posts by Glay Eliver →

Leave a Comment