Development

The Future of JavaScript: ECMAScript 6 and You

Today, JavaScript fills every aspect of our online lives: it checks your e-mail in the background, it guides your online shopping cart, and it even autosaves your blog post as you write. From the client to the server, JavaScript is everywhere. Sometimes it’s hard to remember that this wasn’t always the case.

When I started writing basic web pages in the late 90’s, “DHTML” was the acronym describing the use of JavaScript, HTML, and CSS; the “D” stood for “Dynamic.” DHTML sites were heavy and sluggish, yet they showcased the power of JavaScript (or JScript, depending on who you asked). They also served as a reminder of why many developers shied away from JavaScript at the time: it was resource-intensive, and implementations varied from browser to browser. At the time, I only knew a handful of people who did any kind of web development–we were, after all, more concerned with the issues of how much AP courses “sucked” and whether or not we could get tickets to see Blink 182. For us, the consensus was that JavaScript was for show, and any website could do what it needed to do without it.

JavaScript has now made a name for itself as the go-to for interactive sites. Gone are the days of full-page Flash applications, Shockwave Player, and Java as a general “necessity” for the web. JavaScript has even found it’s way onto the server with projects such as Node.js. Automation of screenshots, converting web pages to PDF, or headless testing can all be achieved from the command link using PhantomJS, a headless implementation of the WebKit engine. On the wider web, JavaScript gives us the little spinner that eventually leads to a table of search results populating without a page reload, or dragging-and-dropping an image to upload it to Imgur. Even some of the apps on the smartphones in pockets around the world use JavaScript. It’s no longer just for hobbyists or experimentation – knowing JavaScript is a part of the job.

Which brings us to ECMAScript 6, or ES6. JavaScript is an implementation of ECMAScript, which also covers languages such as ActionScript, JScript, QtScript, and many others. ES6, codenamed “Harmony,” has been in the works since 2008 and periodic drafts have been published since 2011. This month, June 2015, ECMAScript 6 was formally announced and released and includes a lot of new and interesting tidbits for developers of the modern web.

Below I hope to cover some of the new features, but by no means all of them, as that would be far beyond the scope of this post. For more information, you can check out the full specification PDF to get a look at all of the stuff coming to a browser near you.

Author’s note: the following will include some code examples – some modern browsers may still not recognize certain keywords or agree with their use. For instance, Chrome requires “use strict” to make use of the “let” keyword.

Constants

A simple idea in many languages, Constants have been absent in JavaScript until now. In programming, a constant is similar to a variable, in that you assign a value to an identifier, but differs in that it can never be changed throughout execution of the program. An example in PHP:

define('APPLICATION_VERSION', '1.2.0.4332');
echo APPLICATION_VERSION; // 1.2.0.4332
define('APPLICATION_VERSION', '1.3'); 
// Notice: Constant APPLICATION_VERSION already defined
echo APPLICATION_VERSION; // 1.2.0.4332

The constant APPLICATION_VERSION is defined and can never be altered, and PHP will let you know that if you try (and your error reporting is on). Attempts to redefine the constant will fail, and the original value will hold true. In Javascript, this was previously achieved by the clunky mechanism of defining a new Object property–this was only available in ES5, and only in the global scope. With ES6, things get a lot easier:

const APPLICATION_VERSION = '1.2.0.4332';
console.log(APPLICATION_VERSION); // '1.2.0.4332'
APPLICATION_VERSION = '1.3.0'; // "1.3.0"
console.log(APPLICATION_VERSION); // '1.2.0.4332'
// Notice that the Chrome console evaluated the assignment
// on line 3, however the value didn't change

If we try to actually redefine the constant we get an error:

JavaScript constant redefinition

 

While a simple addition, the introduction of constants to JavaScript shows that the language is maturing in a way that will be welcome by many programmers.

How about something a little more interesting?

Default Parameter Values

If you have programmed in JavaScript, you’ve dealt with all of the ways in which default parameters can be mimicked in the language:

// The "if" way
function say_hi(iterations, greeting, name) {
    if( iterations === undefined ) {
        iterations = 5;
    }

    if( greeting === undefined ) {
        greeting = 'Hello';
    }

    if( name === undefined ) {
        name = 'World';
    }

    for ( var i = 0; i < iterations; i++ ) {
        console.log( greeting + ', ' + name );
    }
}

// The "||" way
function say_hi(iterations, greeting, name) {
    iterations = iterations || 5;
    greeting = greeting || 'Hello';
    name = name || 'World';

    for ( var i = 0; i < iterations; i++ ) {
        console.log( greeting + ', ' + name );
    }
}

// The jQuery "extend" way
function say_hi(args) {
    var params = {};
    var defaults = {
        iterations: 5,
        greeting: 'Hello',
        name: 'World'
    };
    
    jQuery.extend(params, defaults, args);

    for ( var i = 0; i < params.iterations; i++ ) {
        console.log( params.greeting + ', ' + params.name );
    }
}

Above we have several methods to handle “default parameters,” none of which are really ideal. The first method is clunky, the second method is cleaner but not necessarily self-explanatory (especially to novice programmers), and the third method uses jQuery’s “extend” method–this is a great way to define a default set of options in an arguments object, but this also obfuscates the intent of the function – you wouldn’t know it took those arguments just by looking at the method signature, and seeing it in use without one of the object properties defined would leave you oblivious to the fact that you could pass that property without reading the documentation or diving into the source.

ES6 introduces default variables in a way that should be familiar to most programmers. The new method is clean and readable:

function say_hi( iterations = 5, greeting = 'Hello', name = 'World' ) {
    for ( var i = 0; i < iterations; i++ ) {
        console.log( greeting + ', ' + name );
    }
}

At the time of writing, this only works in Firefox (versions 15 and on support basic defaults, while versions 26 and 41 introduce more complex usage). Chrome has an open support ticket to implement this feature in the V8 JavaScript engine, and any browser working towards ES6 should be following suit.

String Interpolation

Something I’ve done for a long time, templating with strings, usually requires custom functionality, regular expressions, and somewhat clunky code. The separation of template and data can hide how things tie together. Here’s an example done with an Ext.JS-like templating function:

function tpl( data, template ) {
    var r = new RegExp();

    for ( var key in data ) {
        if ( ! data.hasOwnProperty( key ) ) {
            continue;
        }

        r.compile( '{' + key + '}', 'g' );
        template = template.replace( r, data[ key  ] );
    }

    return template;
}

var myTplData = {
    name: 'John Smith',
    address: '4124 Rasperry Lane',
    city: 'Heartford',
    state: 'CT'
};

var myTpl = [
    '<div>',
        '<strong>Name: </strong> {name} <br/>',
        '<strong>Street Address: </strong> {address} <br/>',
        '<strong>City, State: </strong> {city}, {state} <br/>',
    '</div>'
].join("\n");

console.log( tpl( myTplData, myTpl ) );

/**
<div>
<strong>Name: </strong> John Smith <br/>
<strong>Street Address: </strong> 4124 Rasperry Lane <br/>
<strong>City, State: </strong> Heartford, CT <br/>
</div>
 */

The above code isn’t exactly great, and rather simple. When you look at Ext.JS’s XTempalte, you see just how much complexity gets added to what sounds like a straightforward concept. Other libraries provide their own methods of binding data to templates, but ES6 can at least begin to replace some of this functionality with an easier approach:

var myTplData = {
    name: 'John Smith',
    address: '4124 Rasperry Lane',
    city: 'Heartford',
    state: 'CT'
};

var myTpl = `
    <div>
        <strong>Name: </strong> ${myTplData.name} <br/>,
        <strong>Street Address: </strong> ${myTplData.address} <br/>,
        <strong>City, State: </strong> ${myTplData.city}, ${myTplData.state} <br/>
    </div>`;

console.log( myTpl );

/**
<div>
    <strong>Name: </strong> John Smith <br/>,
    <strong>Street Address: </strong> 4124 Rasperry Lane <br/>,
    <strong>City, State: </strong> Heartford, CT <br/>
</div>
 */

This completely removes the need for Regular Expressions, and carries a syntax somewhat familiar to those who use PHP and other languages. Integration of variables and strings has been long overdue for JavaScript, so it’s good to see ES6 finally make a change.

And More…

These are just a few of the myriad features coming in ECMAScript 6. While some of these exist in current browser implementations (notably Chrome and Firefox), we likely won’t see the full specification implemented for a few months, and adoption across the board will likely take much longer. That doesn’t mean there aren’t more things to look into and get excited about, such as MapsClassesIterators and Generators, and more.

Comments

1 thought on “The Future of JavaScript: ECMAScript 6 and You

  1. Let me start by saying I greatly appreciate your post. But Ecmascript 6 is a case of too little too late.
    Too little: No rich UI components….but that is really not the point of ecmsScript 6
    Too Late: There are a few Frameworks that solved the issues ecmaScript 6 is solving and they solved them years ago.

    The only frameworks worth mentioning that gives us what ecmascript 6 provides and more is: DOJO, and ExtJs.
    Once a Web Application developer learns OOP, and MVC in a Javascript environment, it becomes clear that ecmaScript6 is late to the punch.

Have a comment?

Your email address will not be published. Required fields are marked *

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupporttwitchunifiedupdatesvaultwebsitewordpress