DEV Community

Discussion on: DAY 2 of building the Higher Order Functions in javascript. the filter Higher Order Function.

Collapse
xtofl profile image
xtofl

I always wondered why one would force the client code to receive the results as an array.

I wonder if it's not better to inject what has to be done with the filtered elements:


names._filter(name => name.length > 5, name => console.log);

var newArray = [];
names._filter(name => name.length > 5, e => newArray.push(e));
...
Enter fullscreen mode Exit fullscreen mode
Collapse
emmanuelonah profile image
Emmanuel Onah Author

Sincerely, I see no reason you wouldn't return a new array to the user, that's the use-case of filter(to filter and return new collection).

Mind you, the injection you assumed above is returning a new array also.

Coming down to your code, I think this is better and readable(don't forget overusing concepts is not the primary aim of programming but rather simplicity to your code-readers like they are reading a book authored by you):

names._filter(name => name.length > 5);

Thank you.

Collapse
xtofl profile image
xtofl

In e.g. python, haskell, c#, ..., filter is conceived as a larger concept, applicable to all iterable objects.

That's why I prefer to stay more generic. It's a design goal you can choose for.

For small arrays, it's ok to return an array.

Thread Thread
emmanuelonah profile image
Emmanuel Onah Author

I really can't say about its usecase for other languages outside Javascript. But then in the context of javascript, i will give you a good example where you can best use it on the web. For example, when trying to handle a client side searching/sorting.... then rather than imperatively handling such operation its better to use the "filter prototype"(a declarative approach) because then the performance which you worry about is already considered by javascript to some extent.