Tags:

w3conf2013

Last week, the annual W3C conference for web professionals, W3Conf 2013, was held in San Francisco. It was packed with tons of interesting talks. The event was professionally organized and it attracted the attention of various Who’s Whos in the front-end development world.

There was an extremely positive vibe, in particular because the theme varies a lot, from ECMAScript 6 to CSS secrets. WiFi worked really well, social medias were flooded with thoughts and opinions from the attendees. There was an ample supply of lunch boxes, snacks, drinks, and even cupcakes to keep everyone energized. The entire conference was live-streamed. In addition to that, Faruk Ateş did a fantastic job of live tweeting the running topic and Chris Coyier posted his excellent notes after every session.

I did a talk on Fluid User Interface with Hardware Acceleration and received a lot of good feedback and follow-up discussion. For those who were not there, check out the slide deck and the following recorded video (make sure you check other talks as well).

Kudos to Doug, Lea, Divya, Liz, and many others who were involved in organizing this amazing conference. See you at W3Conf 2014!

Tags:

Experienced JavaScript programmers take advantage of function expressions, they are used a lot in callbacks, either for DOM access or any other related setup. Another syntax addition to the upcoming ECMAScript 6 is the arrow function expression to let us write a shorter function expression.

A simple way to look at this arrow function notation (section 13.2 in the latest ES6 draft) is as a shorthand form of a normal function expression. This is best illustrated with an example. Say you want to produce the list containing the salary of every employees. By using Array map, it will look like the following snippet:

salaryList = employeeList.map(function (e) { return e.salary; });

Note the function expression as the callback for map() is rather verbose. With an arrow function expression, that construct can be shortened to:

salaryList = employeeList.map(e => e.salary);

No need for function and return. In fact, if you are about to implement the same task with other languages (such as Scala, CoffeeScript, C#), you would end up with a very similar syntax.

How does a syntax tree look like when there is an arrow function? Rather straightforward, no surprise there.

arrow_function

An arrow function expression is designed primary for the case where you need to return a value. However, it still works if you don’t care about returning anything and just want to execute some statements. Take a look at this example:

employeeList.forEach(e => { console.log(e.name); });

Another fun thing with such a shorthand is when you start cascading more functions. For example, if now we are interested in the average salary, this can be computed by:

var total = employeeList.map(e => e.salary).reduce((p, q) => p + q));
var averageSalary = total / employeeList.length;

That’s just way shorter and less crowded compare to function expressions everywhere. It is important to notice that if you have more than one parameter, you need to enclose the parameters with brackets.

Since an arrow function expression is just another form of an assignment expression, we can keep it as a normal object (either for further reuse or just to make it easy to follow), as illustrated in the following fragment (neat, isn’t it?):

var adder = (p, q) => p + q;
var avg = employeeList.map(e => e.salary).reduce(adder) / employeeList.length;

Combine it with array comprehension and magically it does not look to JavaScript-y anymore!

I believe the use of arrow function expression strikes a good balance between readability and expressiveness. What do you think?

Tags:

Many programming languages support the concept of a default argument for a function parameter so that the caller does not always need to specify the argument value. Unfortunately, JavaScript does not have a default argument support in its syntax. This may soon change with the upcoming ECMAScript 6.

A few JavaScript programmers employ various different run-time tricks to achieve the effect of an argument with a default value. The common approach is by leveraging the fact that if an argument is not given a value, then it’s simply undefined.

function foobar(a) { return typeof a; }
foobar(); // "undefined"

This can lead to some code like:

function runApp(appName) { console.log('Running', appName || 'AUTOEXEC.BAT'); }

That function will print Running AUTOEXEC.BAT if invoked as runApp() only (without any argument). The use of logical expression OR (operator ||, see section 11.11 on Binary Logical Operators) means that if the left side (appName) is true (see section 9.2 on ToBoolean), then the short-circuiting kicks in, otherwise we will get the right side (AUTOEXEC.BAT). Note how the result is the same if you execute that function with other value such as null, 0, ![], or even ~~{}.

Another variant which are often encountered is really checking the type of the parameter. Now we can distinguish between undefined and others. Therefore, a suitable value substitution can be carried out.

function runApp(appName) {
  if (typeof appName === 'undefined') appName = 'AUTOEXEC.BAT';
  console.log('Running', appName);
}

In other cases, we really really need to know whether the function is invoked with a certain number of argument or not. For this purpose, the arguments object comes to the rescue.

function runApp(appName) {
  if (arguments.length === 0) appName = 'AUTOEXEC.BAT';
  console.log('Running', appName);
}

All this fancy dance is not necessarily anymore once the syntax itself supports a default argument. In the section 13 of the latest ECMAScript 6 draft, it is mentioned that the formal parameter (for a function) is not a simple list of identifiers anymore (as in ECMAScript 5) as it is generalized to allow BindingElement. While this new construct is there to permit the object and array pattern (see my previous blog post on destructuring assignment), it is important to realize that BindingElement supports an optional initialization, pretty much like in a variable declaration.

In plain English, this means that a function declaration can specify a default value for every parameter. The previous runApp function will turn into something as simple as:

function runApp(appName = 'AUTOEXEC.BAT') {
  console.log('Running', appName);
}

While waiting for browsers and JavaScript engines to implement this feature, such a construct can be used already these days with help of Traceur or TypeScript. It is interesting to note the different desugaring, Traceur will use the arguments object while TypeScript performs the undefined type check.

Having a built-in syntax support for default argument is fantastic. A JavaScript editors could give a better content assist (autocomplete). A code analyzer will be able to track function invocation which omits parameters that do not have default values. I can’t wait until a linter complains to me:

guide.js:42 Specify the non-optional parameter 'stop' to function 'createSeries'

Better language tools will no doubt reduce any coding mistake as best as it can.

Tags:

Scripted (GitHub: github.com/scripted-editor/scripted) is a new JavaScript editing tool from VMware. It is relatively new, the first edition was launched just a few months ago. However, so far it seems to be a capable and usable editor for your JavaScript needs.

Installation is dead easy. Assuming Node.js is running well on your machine, it’s a matter of installing the scripted package (the recent stable is version 0.3). After that, go to your working JavaScript project and launch it:

scripted yourfile.js

Scripted does not have a dedicated GUI. It will launch its interface in your web browser. So far I’ve tried it with the latest Firefox, Chrome, Safari, Opera and they all work quite well.

The main editing component of Scripted is the same as the one used in Eclipse Orion. It has many features you would expect from a modern editor: shortcut keys, split view, syntax highlighting, bracket matching, high-performance scrolling, file search, navigation, autocomplete, and many others. To reduce coding mistakes, Scripted also integrates JSHint for inline analysis. Also, since a typical JavaScript project involves the use of modules, its module dependency solvers will be surely appreciated.

scripted_contentassist

One thing I really from Scripted is its smart autocomplete, or as it is often referred, content assist. Scripted has a type inferencer which consumes your code and deduces the variable and object types (using control flow analysis). The parsing back-end is based on Esprima, with some additional enhancement to make it more tolerable to incomplete construct as the code is still being typed by the user.

In addition to that, Scripted also understands type annotation in the style of Google Closure Compiler, in JSDoc-style comment parsed using Doctrine. For example, if you have the following annotated fragment:

/**
 * Adds two numbers.
 * @param {number} x First number
 * @param {number} y Second number
 * @return {number} The value
 */
function add(x, y) { return x + y; }

and then later on you want to use function add somewhere, Scripted’s content assist (e.g. upon Ctrl+Space) will show that add is accepting x and y and returning a number. If you accept the suggestion, it will prepare the complete function signature add(x, y) for you. Furthermore, content assisting on each parameter will still work and Scripted kindly tells you the required type for each parameter (in this case, a number). If you come from a language with strong/optional typing, this kind of type annotation is quite helpful to reduce the amount of time needed to consult the API documentation.

In its current state right now, Scripted is already usable. It is still actively developed so expect to see more goodies in its upcoming releases. If you are still not sure which JavaScript editor you want to use, give Scripted a try!

Tags:

In a programming language, destructuring assignment denotes the use of patterns to extract parts of an object. If we refer to Common LISP, destructuring assignment binds a set of variables to a corresponding set of values, where normally bind a value to a single variable. For the next-generation ECMAScript 6, destructuring feature is slated to be an important addition to the assignment expression.

Python developers might be already familiar with the concept of sequence unpacking. CoffeeScript also already has the syntax for destructuring. SpiderMonkey, the JavaScript engine in Firefox, has been supporting destructuring assignment for a while. The latest ECMAScript 6 defines the grammar for destructuring assignment in Section 11.13.1. There are two different forms: array pattern and object pattern.

Array Pattern

Variables can be initialized in one go. The following two lines have the same effect, the first one is employing an array pattern.

var [m, d, y] = [3, 14, 1977];
var m = 3, d = 14, y = 1977;

Swapping two variables is rather trivial, this one works just as expected. Internally, it does the sequence as if there is a temporary variable temp and the usual value exchange.

x = 3; y = 4; [x, y] = [y, x]
temp = [y, x]; x = temp[0]; y = temp[1];

Another typical use of array restructuring is for a function which has multiple return values. We don’t need to wrap it in an object anymore. Also, there is no need to accept all elements in the array.

function now() { return [2, 6, 2013, 8, 0]; }
var [m, d] = now(); // m = 2, d = 6
var [,,year] = now(); // year = 2013

With the syntax visualization feature of Esprima, it is rather easy to illustrate the syntax tree of an array pattern. The following figure shows an example thereof. Compared to a vanilla assignment or variable declarator, the obvious different here is that we have an array pattern instead of a plain identifier.

Array pattern syntax tree

Object Pattern

This pattern is very similar, except it works by matching object properties instead of array indices. Thus, we can easily pick the ones we are interested in while ignoring the rest. A similar example as before, e.g. when processing the return value of a function:

function today() { return { d: 6, m: 2, y: 2013 }; }
var { m: month, y: year } = today(); // month = 2, year = 2013

Of course, instead of a pattern, nothing stops you from assigning a holder object before accessing each property. However, the lack of such extra object makes the code looks cleaner (or sweeter, since destructuring is supposed to be a syntactic sugar), in particular when it is part of a loop.

books.forEach(function ({ title: title, author: author }) { console.log(title, author) }; )

In the above construct, every element in that books array may contain a lengthy information about that particular book. Since we just want some properties, it is possible to extract them directly via the object pattern.

It gets even more interesting once we combine with array comprehension. For example, the following line is exactly the same as the above snippet:

[console.log(t,a) for ({title: t, author: a} of books)];

How do you plan to (ab)use array and object pattern?

Tags:

As with many professionals, I am occasionally asked for some random career advice by a few young engineers. Since I am usually not the right person to ask, typically what I share are the thoughts and perspectives which I wish I had when I was still early in my career. One of them is the impact factor.

Pursuing the Trophy

Like many other boys, high school time for you probably means running after the most attractive and charming girl/boy in the class. While you might enjoy the experience, you do need to realize that the rest of your life won’t be spent doing that kind of activity. The challenges in the next stages of life are completely different, anything from forging a long-lasting relationship to the constant-learning of good parenting.

prize

The mantra of achieving early win in a new job often gets translated into being extremely competitive as early as possible. For young and inexperienced engineers, this could lead to being too conscious about the superficial impression. You don’t want to look mediocre and hence you spend the waking hours cranking out the most reliable code possible. You need to prove yourself and kickstart assorted imaginable activities although you quickly run out of time handling every aspect of the project.

You are thrilled to build a faster and better version of your nemesis’ project because obviously you need to be ahead of everyone else. You end up looking too much to the rear-view mirror, growing the (unconscious) fear of being defeated. Chasing the supreme qualities is the name of the game.

Alchemy of Great Vision

At one point, this fast-paced juggling will not be sustainable anymore. You start to compete with a flood of young folks with the fresher and adaptive brain. There are evenings with family obligation, no chance for another round of hackathons (and pizza). A handful of emerging tools, which look alien to you, suddenly empower those youngsters and multiply their intellectual level. Your very own spells are outdated, the rusty magic wand starts to complain. Before you know it, yoga is more attractive to the decaying body than another adrenaline rush.

As you climb the career ladder, individual contribution and technical excellence are still implicitly demanded, they are however not the ultimate (instant) gratification. The goal shifts towards the impact on the team and the organization in general. Instead of coding the fastest possible implementation in a weekend, you are challenged to inspire your peers to build a long-lasting, maintainable project. While achieving an engineering marvel is still in the objective list, a smooth collaboration with the product team, marketing folks, and other stakeholders is higher on the priority. Racing alone to the finish line is a forgotten feat, handling the logistics of the entire troops marching to the conflict zone is the new valued skill.

Being the smartest is useful. However, a real-world battle is far from what Hollywood depicted in Rambo. Adept playmaking, instead of personal glory, is what elevates the game. Inspire others, promote collaborations, and maintain the positive attitude.