loading...

Python versus Javascript map/filter syntax

yujiri8 profile image Ryan Westlund ・1 min read

Python and Javascript both have map and filter, but Python has them as global function that take the sequence as an argument, while Javascript has them as Array methods. There's an interesting tradeoff between the two syntaxes.

Python example:

new = map(transform, old)

Javascript example:

new = old.map(transform)

The appeal of Python's approach is that map and filter can work on any iterable type without that type having to know about them, whereas in Javascript, since they're Array methods, they don't work on pseudo-array types like DOMTokenList and HTMLCollection.

However, Javascript's approach is a bit more readable, but much more readable when you chain it. Consider this Python:

new = map(transform, filter(selector, old))

Versus Javascript:

new = old.filter(selector).map(transform)

That's the big advantage of having it be a method. Of course, Python doesn't suffer from the above grotesquity in practice because it has generator expressions which are way better than that. But since Javascript doesn't have generator expressions, this makes a pretty good reason for implementing map and filter as methods.

Posted on by:

yujiri8 profile

Ryan Westlund

@yujiri8

I'm a programmer, writer, and philosopher. My Github account is yujiri8; all my content besides code is at yujiri.xyz.

Discussion

markdown guide
 

There is nothing bad about Array.from(iterable).map, is it?

Anyways, it seems that Python versions can take multiple iterables at once.

 

Not really anything bad about it, just that it's a lot clunkier than if you could just do iterable.map.