Posted by & filed under Coding.

So let’s take this pretty standard JS + jQuery:

this.names = [];
self = this;
$(['jack','lori','megan']).each( function() {
    self.names.push( this );
} );
console.log( this.name );

We see that type of thing a lot. So much that the function closure in there almost seems like syntactic sugar. But it’s not. It’s a function. And calling it on each item is expensive.

It would be better to just use a ‘for’ loop. But that gives you this nastiness:

this.names = [];
a = ['jack','lori','megan'];
for( i in a ) {
    this.names.push( a[i] );
}
console.log( this.name );

Because natively JS ‘for’ loops return the index. But it is faster, about 10X faster, according to my timings. Since you aren’t calling a closure.

But in Coffeescript it’s even cleaner. Like so:

@names = []
for name in ['jack','lori','megan']
     @names.push( name )
console.log( @names )

Which compiles down to a native for loop and does the index work for you.

It can be even better because you can put the statement before the for:

@names = []
@names.push( name ) for name in ['jack','lori','megan']
console.log( @names )

And it can be even cleaner because the ‘for’ can be used as an expression, like so:

@names = for name in ['jack','lori','megan']
console.log( @names )

And you can even do some filtering, like just taking the odd names, like so:

@names = for name, i in ['jack','lori','megan'] when i % 2 is 0
console.log( @names )

And for IE compatibility we can conditional the call to ‘console’ since &^*(%^&%! IE doens’t support the console.

@names = for name, i in ['jack','lori','megan'] when i % 2 is 0
console?.log( @names )

Coffeescript. It’s good.

Leave a Reply

  • (will not be published)