Blog
Vars And Values
Sometimes I hear JavaScript dev throw around the terms vars and values as synonyms for each other. Realising that they’re not was a serious ‘aha’ moment for me - and making the distinction about it can make talking and thinking about code clearer by far.
Tapping Into The Method Chain
Objects and methods are a big deal. They’re the core way in which JavaScript defines functionality against a type; which is reflected in the standard library, in many of the libraries we choose to use, and how production code tends to be written (at least, in my experience).
Compare these two solutions for returning the name of all the audiophiles in a contact book:
var contacts = [
{ name: 'Jen', interests: ['audio', 'gaming', 'running'] },
{ name: 'Ben', interests: ['skating', 'eating', 'tap-dancing'] },
{ name: 'Ken', interests: ['partying', 'life in plastic', 'audio'] }
]
A first-pass underscore solution might look something like this:
var audiophileP = function(contact){ return _.contains(contact.interests, 'audio') },
getName = function(contact){ return contact.name }
_.map(_.filter(contacts, audiophileP), getName)
//= ["Jen", "Ken"]
The same can be achieved by chaining native methods:
contacts.filter(audiophileP).map(getName)
//= ["Jen", "Ken"]
The second is far cleaner, and easier to read; especially as transformations grow beyond a handful of steps. Many libraries recognise this, providing APIs that are designed to be chained; commonly called Fluent APIs. Underscore even ships its own version, allowing you to use all of underscores methods with any object, at the price of a little boilerplate:
_.chain(contacts).filter(audiophileP).map(getName).value()
//= ["Jen", "Ken"]
The ordering is clear, but the intent is somewhat obscured.
Jslint Is Not A Code Quality Tool For 3rd Party Code
Doug Crockford’s JSLint performs static analysis on Javascript, returning a list of what Crockford considers to be violations of best practice. Contrary to the assertions of its creator, however, it is not a fit tool by which to judge the quality of 3rd party code.
Prototypes: The Short(est Possible) Story
Prototypal inheritance is a brilliantly simple concept. Javascript’s syntax, however, often confuses new-comers. Let’s solve that, ehy?