My new blog here at

Sunday, December 23, 2012

Coffeescript's destructuring assignment is cool

This article is about feature that can simplify your life while you are writing on coffeescript.

This feature saves you from writing boilerplate code for accessing objects properties.

 Here is the basic example for those who doesn't understand what is destructuring assignment means:

user = {name: "Alex", age: 10, email: ""}

{name, age} = user

name is "Alex" # true
age is 10 # true

And that's nice. Another cool examples here But at the first time when i saw this i haven't understood all the beauty of such feature. Here is some cases of using destructuring assignment that were not highlighted in official coffeescript site.

Parsing arguments to functions:

some_func = ({name, age}) ->
    console.log "Name #{name}. Age #{age}"

user = {name: "Alex", age: 10, email: ""}
some_func user # Name Alex. Age 10

The great thing in this example is that arguments order doesn't matter. In future we may add some another one, and we don't need to rewrite our code for fixing arguments order.

We need to go deeper ...

Let's add address property to our user

user = 
    name: "Alex"
        city: "Amsterdam"
        street: "GreenSt"

# and now imagine that we have a list of users 
# users = [user1, user2, ..
# And we need to get all users from Amsterdam

result = users.filter ({address: {city, street}) ->
    city is "Amsterdam"

As we can see this works with any depths. And this is awesome when you need to select multiple filter criteria from big objects, or just select them via map function this prevents you from writing boilerplate code for accessing the  objects properties.

This looks nice in case when we are requiring something, for instance in nodejs or in simple commonjs modules :

{readFileSync} = require 'fs' 
# gets fs.readFileSync and assigns it to local variable readFileSync

As you can see this is very simple but very powerful feature.

Thanks for reading this, feel free to correct me if something is wrong =)