I got an email the other day from someone reading through jQuery Fundamentals – they’d come across the section about patterns for performance and compression, which is based on a presentation by Paul Irish gave back at the 2009 jQuery Conference in Boston.
In that section, there’s a bit about alternative patterns for flow control – that is, deciding what a program should do next. We’re all familiar with the standard if statement:
1 2 3 4 5 6 7
What stumped the person who emailed me, though, was when the same logic as we see above was written like this:
1 2 3 4 5 6 7
What’s happening here is that we’re using a throwaway object literal to express
the conditions under which we will say a
thing is an animal. We could have
stored the object in a variable first:
1 2 3 4 5 6 7 8 9 10 11 12
The pattern works with an array, too:
1 2 3
It’s also useful for looking up values generally, which is how I find myself using it most often these days in my work with Toura, where we routinely branch our code depending on the form factor of the device we’re targeting:
1 2 3 4 5 6
As an added benefit, constructs that use this pattern will return the
undefined if you try to look up a value that doesn’t have
a corresponding property in the object literal.
A great way to come across techniques like this is to read the source code of your favorite library (and other libraries too). Unfortunately, once discovered, these patterns can be difficult to decipher, even if you have pretty good Google fu. Just in case your neighborhood blogger isn’t available, IRC is alive and well in 2011, and it’s an excellent place to get access to smart folks eager to take the time to explain.