Sunday, May 12, 2013

Destructuring Assignment: Another Case for CoffeeScript

Often times, a single options parameter is passed into a JavaScript function.

In that called function, we will then split up the options argument into separate variables to used later.

Javascript

Here's how it's frequently done in Javascript:


var options;

options = {
  id: 1,
  name: "bob",
  address: "123 main street",
  city: "new york",
  state: "ny",
  zip: 10027
};

({
  myFunction: function(options) {
    var address, city, id, name, state, title, zip;

    id = options.id
    name = options.name
    title = options.title
    address = options.address
    city = options.city
    state = options.state
    zip = options.zip;

    return console.log('name', name);
  }
});


CoffeeScript

Here's how it can be done in CoffeeScript:


options =
  id: 1
  name: "bob"
  address: "123 main street"
  city: "new york"
  state: "ny"
  zip: 10027
  

myFunction: (options) ->
  { id, name, title, address, city, state, zip } = options  # << Destructing Assignment
  console.log 'name', name


The CoffeeScript implementation, using Destructing Assignment is a nice improvement.



Javascript 1.7

Granted Javascript 1.7 provides Destructing Assignment, but if you rely on that, then you'll need to worry about end user browser compatibility and the higher likely hood of developers falling into the trap of using proprietary extra non-cross-browser features, e.g., Mozilla's for each.

Conclusion

This is one small example of why you should be using CoffeeScript instead of raw Javascript.

Here are a few more reasons to use CoffeeScript:
  • Fewer lines to write and maintain
  • More expressive (easier to understand) code
  • String interpolation
  • Consistent, readable, pretty-printed generated Javascript
  • Generally runs faster than typical Javascript hard-coded "equivalent" code


References

http://jashkenas.github.io/coffee-script/
http://js2coffee.org/


No comments:

Post a Comment