Make your code readable and expressive
There are numerous practices and heuristics to make a code more readable, expressive, and clean. We will cover this topic later on, but here we will talk about syntactic sugar. The term means an alternative syntax that makes the code more expressive and readable. In fact, we already had some of this in JavaScript from the very beginning. For instance, the increment/decrement and addition/subtraction assignment operators inherited from C. foo++ is syntactic sugar for foo = foo + 1, and foo += bar is a shorter form for foo = foo + bar. Besides, we have a few tricks that serve the same purpose.
JavaScript applies logical expressions to so-called short-circuit evaluation. This means that an expression is read left to right, but as soon as the condition result is determined at an early stage, the expression tail is not evaluated. If we have true || false || false, the interpreter will know from the first test that the result is true regardless of other tests. So the false || false part is not evaluated, and this opens a way for creativity.
Function argument default value
When we need to specify default values for parameters we can do like that:
function stub( foo ) { return foo || "Default value"; } console.log( stub( "My value" ) ); // My value console.log( stub() ); // Default value
What is going on here? When foo
is true
(not undefined
, NaN
, null
, false
, 0
, or ""
), the result of the logical expression is foo
otherwise the expression is evaluated until Default value
and this is the final result.
Starting with 6th edition of EcmaScript (specification of JavaScript language) we can use nicer syntax:
function stub( foo = "Default value" ) {
return foo;
}
Conditional invocation
While composing our code we shorten it on conditions:"
var age = 20; age >= 18 && console.log( "You are allowed to play this game" ); age >= 18 || console.log( "The game is restricted to 18 and over" );
In the preceding example, we used the AND (&&
) operator to invoke console.log
if the left-hand condition is Truthy. The OR (||
) operator does the opposite, it calls console.log
if the condition is Falsy
.
I think the most common case in practice is the shorthand condition where the function is called only when it is provided:
/**
* @param {Function} [cb] - callback
*/
function fn( cb ) {
cb && cb();
};
The following is one more example on this:
/** * @class AbstractFoo */ AbstractFoo = function(){ // call this.init if the subclass has init method this.init && this.init(); };
Syntactic sugar was introduced to its full extent to the JavaScript world only with the advance in CoffeeScript, a subset of the language that trans-compiles (compiles source-to-source) into JavaScript. Actually CoffeeScript, inspired by Ruby, Python, and Haskell, has unlocked arrow-functions, spreads, and other syntax to JavaScript developers. In 2011, Brendan Eich (the author of JavaScript) admitted that CoffeeScript influenced him in his work on EcmaScript Harmony, which was finalized this summer in ECMA-262 6th edition specification. From a marketing perspective, the specification writers agreed on using a new name convention that calls the 6th edition as EcmaScript 2015 and the 7th edition as EcmaScript 2016. Yet the community is used to abbreviations such as ES6 and ES7. To avoid confusion further in the book, we will refer to the specifications by these names. Now we can look at how this affects the new JavaScript.
Arrow functions
Traditional function expression may look like this:
function( param1, param2 ){ /* function body */ }
When declaring an expression using the arrow function (aka fat arrow function) syntax, we will have this in a less verbose form, as shown in the following:
( param1, param2 ) => { /* function body */ }
In my opinion, we don't gain much with this. But if we need, let's say, an array method callback, the traditional form would be as follows:
function( param1, param2 ){ return expression; }
Now the equivalent arrow function becomes shorter, as shown here:
( param1, param2 ) => expression
We may do filtering in an array this way:
// filter all the array elements greater than 2 var res = [ 1, 2, 3, 4 ].filter(function( v ){ return v > 2; }) console.log( res ); // [3,4]
Using an array function, we can do filtering in a cleaner form:
var res = [ 1, 2, 3, 4 ].filter( v => v > 2 ); console.log( res ); // [3,4]
Besides shorter function declaration syntax, the arrow functions bring the so called lexical this
. Instead of creating its own context, it uses the context of the surrounding object as shown here:
"use strict"; /** * @class View */ let View = function(){ let button = document.querySelector( "[data-bind=\"btn\"]" ); /** * Handle button clicked event * @private */ this.onClick = function(){ console.log( "Button clicked" ); }; button.addEventListener( "click", () => { // we can safely refer surrounding object members this.onClick(); }, false ); }
In the preceding example, we subscribed a handler function to a DOM event (click
). Within the scope of the handler, we still have access to the view context (this
), so we don't need to bind the handler to the outer scope or pass it as a variable through the closure:
var that = this; button.addEventListener( "click", function(){ // cross-cutting concerns that.onClick(); }, false );
Method definitions
As mentioned in the preceding section, arrow functions can be quite handy when declaring small inline callbacks, but always applying it for a shorter syntax is controversial. However, ES6 provides new alternative method definition syntax besides the arrow functions. The old-school method declaration may look as follows:
var foo = { bar: function( param1, param2 ) { } }
In ES6 we can get rid of the function keyword and the colon. So the preceding code can be put this way:
let foo = { bar ( param1, param2 ) { } }
The rest operator
Another syntax structure that was borrowed from CoffeeScript came to JavaScript as the rest operator (albeit, the approach is called splats in CoffeeScript).
When we had a few mandatory function parameters and an unknown number of rest parameters, we used to do something like this:
"use strict"; var cb = function() { // all available parameters into an array var args = [].slice.call( arguments ), // the first array element to foo and shift foo = args.shift(), // the new first array element to bar and shift bar = args.shift(); console.log( foo, bar, args ); }; cb( "foo", "bar", 1, 2, 3 ); // foo bar [1, 2, 3]
Now check out how expressive this code becomes in ES6:
let cb = function( foo, bar, ...args ) { console.log( foo, bar, args ); } cb( "foo", "bar", 1, 2, 3 ); // foo bar [1, 2, 3]
Function parameters aren't the only application of the rest operator. For example, we can use it in destructions as well, as follows:
let [ bar, ...others ] = [ "bar", "foo", "baz", "qux" ]; console.log([ bar, others ]); // ["bar",["foo","baz","qux"]]
The spread operator
Similarly, we can spread array elements into arguments:
let args = [ 2015, 6, 17 ], relDate = new Date( ...args ); console.log( relDate.toString() ); // Fri Jul 17 2015 00:00:00 GMT+0200 (CEST)
ES6 also provides expressive syntactic sugar for object creation and inheritance, but we will examine this later in The most effective way of declaring objects section.