Array.prototype.myFilter = function (callback) {
const newArray = [];
// Only change code below this line
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this) == true) {
newArray.push(this[i]);
}
}
//This function works like filter()
return newArray;
};
I need help to understand how callback function works, and how we can implement it?
The code that was given above is just an example, I just need help with this topic
Dont be haters, I need explanations, I am just an entry-level javascript programmer
Thanks
2
Answers
Since you are a beginner I suppose you need explanation not the coding part. So here it is:
Any function that is passed into the argument of some other function like suppose you have this type of function " FunctionA(functionB) is referred to as the call back function.
These functions play a pivotal role in javascript since they allow dynamic programming to be implemented at best.
In your case, you are using myFilter method that works similar to the filter method in javascript.
You can filter the elements based on the specific condition that you provide to this filter method.
I hope you will get a better understanding now. Thanks
This can work, here in the test function we keep only the elements with a length greater than 4 letters so it will return :
Array [ "bacon", "eggs bacon spam and sausage" ]
Have a nice day.