Chris Pickett

Don't Try This Vol. I

Javascript | Sept. 6, 2013, 9:31 p.m. | 1 min read

I'm a huge fan of list comprehensions in Python. It's always made me a bit frustrated when I can't use them in other languages such as Javascript.... But Wait, Can I?

List Comprehensions

DISCLAIMER: This is not good code. Please don't ever do this.

If you're not careful list comprehensions can spin wildly out of control (I'm looking at you nested comprehensions), but overall I think they're a very useful contstuct. It's always made me a bit frustrated when I can't use them in other languages such as Javascript.

But Wait, Can I?

I was reviewing some code at work and I ran across a snippet of javascript that was something like:

for(var i = 0; myMethod(arrayOfObjects[i]), i < arrayOfObjects; i++);

This is essentially a poor-man's .map, it works by overloading the conditional portion of javascript's for loop, this works because the conditional is re-evaluated on every iteration of the loop. This means that it's possible to create a proto-comprehension:

var array = [];
for(var i = 0; (i % 2 == 0) ? array.push(i) : null, i < 10; i++);

After running that snippet, array would contain: [0, 2, 4, 6, 8, 10]. This is essentially doing the same thing as the code above, but instead of calling a method on each item in the array I'm using a ternary as an if statement and pushing only the ones I want onto the array.

This could also be used to get a specific key out of a list of objects:

var arrayOfObjects = [
        year: 2013,
        make: 'Toyota'
        year: 2011,
        make: 'Mazda'
        year: 1985,
        make: 'Honda'

var makes = [];

for(var i = 0; makes.push(arrayOfObjects[i].make), i < arrayOfObjects.length - 1; i++);

Which would give us: ["Toyota", "Mazda", "Honda"]. Here we loop through each of the objects and push the make property into the makes array. One interesting note is that .length - 1 is required. If we left that off, i would actually get incremented to 4 (even though there are only 3 items in the array), because it's the conditional (the part we're overloading) that tells the loop to break.

Again, just to be clear, I'm by no means saying that one should do this, but it's interesting to play with.


comments powered by Disqus