JavaScript Array.filter() — What does this output?
This is a daily Javascript challenge from the CodeShot archive. Practice your knowledge of Filter Objects By Property Instock and improve your technical interview readiness.
const inventory = [
{ item: "apple", count: 5 },
{ item: "banana", count: 0 },
{ item: "cherry", count: 3 }
]
const inStock = inventory.filter(i => i.count > 0)
console.log(inStock.length)
Detailed Explanation
Why This Question Matters
If you've been coding in JavaScript for a while, .filter() feels like second nature. But when you see it in a technical interview or a certification quiz, it's easy to overthink it.
The core of this challenge isn't actually about the .filter() method itself—it's about understanding how JavaScript handles truthy and falsy values, and how array methods return new data structures. Many developers trip up here because they confuse .filter() with .find() or mistakenly think it modifies the original array.
Getting this right is the difference between writing clean, functional code and chasing bugs because you didn't realize your array was empty or contained an unexpected element.
Understanding the Code
Let's look at the snippet:
Here is what's happening under the hood.
First, we have an array of objects. This is a standard way to represent data coming from an API or a database. Each object has a count property.
Then we call .filter(). The filter method iterates through every single element in the inventory array. For each element (which we've named i in the arrow function), it runs a test: i.count > 0.
If that expression returns true, the element is kept and added to a new array. If it returns false, it's tossed out.
1. Apple: 5 > 0 is true. (Keep it)
2. Banana: 0 > 0 is false. (Discard it)
3. Cherry: 3 > 0 is true. (Keep it)
The variable inStock now holds a new array containing only the apple and cherry objects. Finally, we call .length on that new array. Since there are two items left, the output is 2.
Finding the Correct Answer
The correct answer is Option B (2).
Why not other options?
Some people might guess 3 because they see three objects in the original list and forget that .filter() actually removes elements. Others might guess 1 if they misread the logic or think the code is looking for a specific item.
The key is remembering that .filter() doesn't just "check" the array; it creates a shallow copy containing only the elements that passed the test. Since two items passed, the length of the resulting array is 2.
Common Mistakes Developers Make
Even mid-level devs occasionally make these mistakes when working with array methods:
1. Confusing .filter() with .find()
This is the biggest one. .find() returns the first element that matches the criteria. If we used .find() here, inStock would be the apple object { item: "apple", count: 5 }, and calling .length on an object would return undefined.
2. Mutating the original array
Beginners often think .filter() changes the inventory array. It doesn't. The original inventory still has three items. If you need to update the original list, you have to reassign the variable (if using let) or create a new state.
3. Truthy/Falsy pitfalls
In this example, we used i.count > 0. But if a developer wrote inventory.filter(i => i.count), they might get unexpected results. In JavaScript, 0 is falsy. So i => i.count would actually work the same way here, but it's riskier. If count was undefined or null, the logic behaves differently. Being explicit with > 0 is always the safer bet.
Real-World Usage
In a production environment, you aren't just filtering apples and bananas. You're filtering thousands of rows of data.
You'll see this pattern everywhere:
- E-commerce: Filtering a product list by price range or availability.
- Dashboards: Showing only "Active" users from a list of all registered accounts.
- UI State: Removing a deleted item from a local state array before sending the update to the server.
For example, if you're building a shopping cart, you might use this to calculate the total price of only the items that are actually in stock:
Combining .filter() with .map() or .reduce() is the bread and butter of modern JavaScript development, especially in frameworks like React where immutability is key.
Key Takeaways
- .filter() creates a new array; it does not mutate the original.
- The callback function must return a boolean (true or false) to determine if the item stays.
- Always distinguish between .filter() (returns an array) and .find() (returns a single element).
- Be explicit with your comparisons (e.g., > 0) to avoid bugs with JavaScript's truthy/falsy logic.
Why this matters
Understanding Filter Objects By Property Instock is crucial for passing technical interviews. In real-world applications, this concept often leads to subtle bugs if not handled correctly. For more details, you can always refer to the official MDN Documentation.