Nested properties initialization – syntactic sugar

I think most of developers are familiar with the object syntax initializer, which basically allows you to set up values of properties just like that

In this example the Settings property is assigned with new instance of CustomWebClientSettings class. However for time to time we only want to change particular property of given nested property and leave rest of the object intact. Of course we can write it usual way

but there is a much cooler syntax for that. The code above can be rewritten to

Note that there is no new keyword in the assignment of Settings property, which means that the Settings object is updated with the values of properties in braces. Of course this syntax can be safely used only if the nested property(in this case Settings) is initialized up front in constructor, otherwise you will get NullReferenceException. Source code for this post can be found here

Nested properties initialization – syntactic sugar

Using ECMAScript6 today

1. Introduction

Although ECMAScript6 has not been officially released yet, we can play around with new language features today. There are tools such as Traceur or Babel which are able to convert ECMAScript6 into ECMASciprt5, thus we are able to run the code in every browser. So let’s try to run the snippet below, which leverages destructuring assignmentusing those tools

2. Using Traceur

I’ll start from Traceur first. First of all we have to install it, so run in console (I am using gulp as my build system)

Then we have to write simple gulp task which:

  • grabs all of our js files
  • runs the code analysis using JsHint
  • transpiles source files into valid ECMAScript5
  • concatenates the result into single file
  • generates source maps (for debugging proposes)

Having our result file ready, now we can add a script tag in html pointing to app.all.js. However at this point in the runtime we will get an error.

ECMAScript6 today
Quick look at the generated app.all.js file reveals the problem

Transpiled code has references to $traceurRuntime objects, so in order to make our code work, we have to add additional script tag pointing to traceur-runtime.js. You can easily get the sources with bower, just run in console

Now everything should work and in console we’ll get expected result
ECMAScript6 today
As you could see in example above Traceur generates overcomplicated code which makes debugging of the original sources (using source maps) a painful process. Just take a look at the following screenshot
ECMAScript6 today
fortunately Babel doesn’t seem to have these drawbacks.

3. Using Babel

Let’s modify our gulp build script to use Babel instead of Traceur

And basically that all, we are ready to go. Babel doesn’t require any runtime dependencies, generated code is simple

and even source maps seem to work correctly.
ECMAScript6 today
So when it comes to me I choose Babel. Source code for this post can be found here

Using ECMAScript6 today