While learning JavaScript, I came across two important concepts: Callback Functions and the array filter() method.
At first, they looked confusing, but simple examples made them much easier to understand.
What is a Callback Function?
A callback function is a function that is passed as an argument to another function.
Example:
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function message() {
console.log("Welcome to JavaScript!");
}
greet("Narasimma", message);
Here, message is passed to greet() as a callback function.
Simple Way to Remember 💡
A callback is simply a function given to another function to be called later.
What is filter()? 🔍
filter() is a JavaScript array method used to select elements that match a condition.
Example:
let numbers = [10, 15, 20, 25, 30];
let result = numbers.filter(function(number) {
return number > 20;
});
console.log(result);
Output:
[25, 30]
The filter() method checks every element and keeps only the elements where the condition is true.
Using Arrow Function
We can write the same code in a shorter way:
let numbers = [10, 15, 20, 25, 30];
let result = numbers.filter(number => number > 20);
console.log(result);
filter() with Objects
We can also filter objects.
let students = [
{ name: "Arun", age: 20 },
{ name: "Kumar", age: 17 },
{ name: "Ravi", age: 22 }
];
let adults = students.filter(student => student.age >= 18);
console.log(adults);
This returns only the students whose age is 18 or above.
Callback + filter()
Now we can connect both concepts.
The function passed inside filter() is a callback function.
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers);
Output:
[2, 4]
So, filter() uses a callback function to check each array element.
Easy Way to Remember 🧠
Callback Function → A function passed to another function.
filter() → Selects elements based on a condition.
Array
↓
filter()
↓
Callback checks each item
↓
Condition true?
↓
Keep the item ✅
Conclusion
Today I learned that callback functions are an important part of JavaScript, and filter() is a very useful array method.
These concepts are especially useful when working with arrays, objects, APIs, and real-world JavaScript applications.
Learn → Practice → Build 🚀
Top comments (0)