0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Filter in JavaScript: Simple Guide with Examples

Use the filter method on an array to create a new array with elements that pass a test defined by a callback function. The callback receives each element and returns true to keep it or false to exclude it.
📐

Syntax

The filter method is called on an array and takes a callback function as an argument. This callback runs for each element and should return true to keep the element or false to remove it.

  • array.filter(callback(element, index, array))
  • element: The current item being processed.
  • index: The position of the current item (optional).
  • array: The original array (optional).
javascript
const newArray = array.filter((element, index, array) => {
  // return true to keep element, false to skip
  return true; // example placeholder
});
💻

Example

This example shows how to filter an array of numbers to keep only even numbers.

javascript
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens);
Output
[2, 4, 6]
⚠️

Common Pitfalls

One common mistake is forgetting to return a boolean value from the callback, which results in an empty array or unexpected results. Another is modifying the original array inside the callback, which can cause bugs.

javascript
const nums = [1, 2, 3, 4];

// Wrong: no return, so filter returns empty array
const wrong = nums.filter(num => { return num > 2; });
console.log(wrong); // [3, 4]

// Right: return the condition
const right = nums.filter(num => num > 2);
console.log(right); // [3, 4]
Output
[3, 4] [3, 4]
📊

Quick Reference

MethodDescription
filter(callback)Creates a new array with elements passing the test.
callback(element)Function that returns true to keep element.
ReturnsA new filtered array, original array unchanged.

Key Takeaways

Use filter to create a new array with elements that pass a test.
The callback must return true to keep an element, false to exclude it.
The original array is not changed by filter.
Always return a boolean from the callback to avoid empty results.
Avoid modifying the array inside the filter callback to prevent bugs.