JavaScript The New Parts

0
4763

Magnifying Glass with visual

ECMAScript2015 (ES6) is the specification that defines new features in JavaScript. In the second part of this series on JavaScript, let us look at new features like the binary/octal literals and enhanced object literals.

In the first part of this series, we covered the direction in which JavaScript (JS) is evolving. We also briefly looked at the new themes in the ECMAScript2015 specifications, before going on to cover block scope and template strings. And we explored two environments where you could try the new version —es6fiddle.net and transpilers.
In this part, we will cover more JS environments and look at the level of coverage in each of them. The browser environment has a ready to use debug environment.
Table 1 lists the level of coverage for features explained in the earlier article.

Table 1
(None: 0 per cent; Low: >0-30 per cent; Medium: 30-70 per cent; High: 70-95 per cent; Full: 100 per cent)

tabl1

Language environments and their support

io.js: io.js is a famous fork of node.js that was created with the intention of having community control over the future of the compatible node.js environment. io.js has far more ES6 feature support than node.js. Learning new JavaScript features could be a compelling reason for you to move from node.js to io.js, which is a JS parser with a command line from which you can directly try ES6 features. Setting up io.js is covered in the next section.
Babel: This is more than a translator for ES6-to-ES5 conversion. Babel is recommended to JS enthusiasts who love to understand the nuances of language better. You can see how ES6 features can be implemented with ES5. If you are keen to learn about compilers, you can do so by dissecting Babel, which has been developed by a JS enthusiast with the intention to learn JavaScript!
Node.js: Node.js support for ES6 features is limited. Please note that in some cases, you may need to enable a –harmony* flag to get the required feature support. For simplicity of representation, the need for flag-enabling is not explicitly mentioned in the table.
In browser environments, though the current version of Chrome seems to support ES6 better (w.r.t. features covered in Parts 1 and 2 of this series), the beta and nightly versions of Firefox have better overall ES6 support than Google Chrome. If you are a Google Chrome fan, consider switching to Firefox to experiment with ES6 from within browser environments.

Setting up io.js
Visit https://iojs.org/en/index.html and download the bundle. In the Linux (Ubuntu) environment, io.js is just a Zip file to be downloaded and unzipped. You can create a soft link to the node.js file, if you would like to have a single JS environment. io.js claims maximum compatibility with node.js. But if your intention to try io.js is only ES6, you can use io.js separately. Begin by issuing the following code:

janardan@ubuntu:~$ iojs --version
v3.1.0
janardan@ubuntu:~$ iojs
> greet = “Hello, io.js”;
‘Hello, io.js’
> console.log(`Message: ${greet}`);
Message: Hello, io.js

From the command line, I tested the template string feature. To exit from the command line, type .exit (dot exit).
Here’s a sample snippet of how node.js will behave for the same input.

janardan@ubuntu:~$ node --version
v0.12.6
janardan@ubuntu:~$ node
> greet = “Hello, node.js”;
‘Hello, node.js’
> console.log(`Message: ${greet}`);
...

In the last statement, as node.js does not understand backtick, the node continues to expect input from the user by giving ellipses.
This month, I cover topics that are really additions to existing ES5, rather than entirely new features.
The literals are supported as part of the theme, where JS should go low-level (as in close to the machine and bits). This is useful for programmers doing bit manipulations, such as file permissions or network packet processing.
The array, string and math library is to eliminate the need for programmers to use other libraries (such as Underscore.js), or to code their own helper functions.

Binary and octal literals
There are two new number literals that have been added to JavaScript. These are the binary and octal literals. This is actually a re-introduction from previous releases.
The 0b (zero-b) prefix is for the binary numbers and 0o (zero-oh) prefix is for octal numbers.

> 0b111 // Output: 7 (decimal)

The output is in decimal.

> 0b11+0o11  // Output: 12 (3+9)

The following is the sum of the binary literal and the octal literal. The result is decimal.

> 0b11+0o11+0x11+011 // Output: 38

The following is the sum illustrating binary, octal, hex and octal. Note that JS interpreters still support 0 (zero) prefix notation for octal.

> “use strict”; 0b11+0o11+0x11+011
SyntaxError: Octal literals are not allowed in strict mode.

When you run the same in use strict mode, you get an error as only the 0 (zero) prefix octal is deprecated.

Enhanced object literals
Enhancements to object literals involve a cluster of features rather than a single one. The first is shorthand for object properties at the time of initialisation. Shown below is an example that best explains it. The second enhancement is the shorthand for object methods, and the third is computed property names.

Properties shorthand
In ES5, when we constructed object properties with scalar variables, we repeated the variable names like what’s shown below in Snippet 1:

let firstname = “Janardan”,
lastname = “Revuru”,
organization = “HP EG India R&D”;

let employee = {
firstname: firstname,
lastname: lastname,
organization: organization,
};

Snippet 1: Longform notation

In ES6, we can avoid the repetition of object properties and variables names, if they are the same, as shown below in Snippet 2:

let employee = {
firstname,
lastname,
organization,
};

Snippet 2: Shorthand notation

You can even mix shorthand notation with direct initialisation, like what’s shown below in Snippet 3:

let employee = {
firstname,
lastname,
org: organization,
location: “Mahadevapura”
};

Snippet 3: Mixed notation

Method shorthand
ES6 also provides shorthand notation for the method definitions. You can eliminate the keyword ‘function’ when defining method properties.
Extending Snippet 2, we can write the code as shown below. You will notice that you eliminated writing the print: function { } to define a method.

let payroll = {
_employees: [],
print() {
console.log(JSON.stringify(employee));
}
};
payroll.print();

Output:
{“firstname”:”Janardan”,”lastname”:”Revuru”,”organization”:”HP EG India R&D”}

The full code snippet is available at http://www.es6fiddle.net/iedsjidz/

Table 2
(None: 0 per cent; Full: 100 per cent)

tabl2

Why learn JavaScript?
In the crowded space in which new programming languages emerge every year, with each ‘selling’ itself as the best ever in the history of computing, how can programmers decide or choose between them?
Over the years, what I have learnt is, it is not the most elegant and feature-rich language that survives the test of time. For a language to continue being in use, there are many factors that come into play. JavaScript has stood the test of time, to some extent, on the basis of its own merits and partly due to luck.
JavaScript does have its share of imperfections. But the sheer omnipresent nature of the JavaScript environment inside browsers on different platforms makes it the most used. With ES6, there are enough reasons to make JavaScript more compiler and translator friendly. This will enable the bulk of programs already written in languages like C/C++ to be translated to JavaScript to run in a browser environment. Some examples are the GWT compiler that translates Java source to JavaScript source, and Sharp# which converts the JavaScript environment. For a list of languages that compile to JavaScript, visit https://github.com/jashkenas/coffeescript/wiki/List-of-languages-that-compile-to-JS. So even if you are a non-JavaScript programmer, who wants your application to run in a browser environment, it is essential you understand the fundamental capabilities and limitations of the language.
If you are a graduate out of college or in the early years of your software career, you can bet your career on JavaScript—as some sort of ‘one language that fits all purposes’, be it developing hobby mobile apps or enterprise class applications. JavaScript has made inroads into the server side too. Thanks to node.js and JSON data interchange, now server side programmers and client side programmers talk the same language! They also exchange data in common JSON format.
To know more about the layers JavaScript is striving, log on to the URL mentioned in Reference 3.
Next month we will cover computed property keys and String functions in ES6.

References
[1 ‘Play around with ES6 features online’; http://www.es6fiddle.net/
[2] ‘Languages that compile to JavaScript’ https://github.com/jashkenas/coffeescript/wiki/List-of-languages-that-compile-to-JS
[3] ‘An Introduction to Full-Stack JavaScript’; http://www.smashingmagazine.com/2013/11/introduction-to-full-stack-javascript/

LEAVE A REPLY

Please enter your comment!
Please enter your name here