ES6: The best parts

ES6

ES6 (or ECMAScript 2015 as it is officially titled) offers a lot of new features, here are the ones that you should be using now (if your end product doesn’t lean too heavily on older browsers), and one that you should avoid.

Note

Browser support for these features is obviously a moving target, to verify if the features below have support in a particular browser, refer to this chart.

Arrow Functions

Arrow Functions are a shorthand way of writing out functions. Arrow functions make our code more concise, and simplify function scoping and the this keyword. Using arrow function allows us to avoid typing the function keyword, return keyword (it’s implicit in arrow functions), and curly brackets.

Instead of this:

function foo(x) {
    return x;
}

you would write this:

var foo = (x) => {
    return x;
}

It’s good to note that parentheses are optional when there is only one parameter:

var foo = x => {
    return x;
}

Oddly enough, parentheses are required when there are no parameters:

var bar = () => {
    return 'bar';
}

Object Literal Syntax

Arrow functions, like function expressions, can be used to return an object literal expression. The only caveat is that the body needs to be wrapped in parentheses, in order to distinguish between a block and an object (both of which use curly brackets).

ES5

var createPerson = function (name,age) {
    return {
        name: name,
        age: age
    }
}

ES6

var createPerson = (name,age) => ({
    name: name,
    age: age
})

Even better, if the objects name/values are the same, you can shorten to this:

var createPerson = (name,age) => ({
    name,
    age
})

Odds and Ends

This

The ‘this’ keyword words differently in arrow functions. For example, methods like call(), apply(), and bind() will not change the value of this when being used in an arrow function.

Constructors

Attempting to use the keyword ‘new’ with arrow functions will throw an error. Arrow functions (as methods do) lack a prototype property or other internal methods.

Generators

Arrow functions can not be used as function generators in ES6. Using the yield keyword in ES6 will throw an error. If you need a generator in ES6, use the new generator syntax.

Support

As of this writing, support for arrow functions is widespread in:

  • Chrome
  • Safari
  • Firefox
  • MS Edge

If you need to support Internet Explorer (any version), be advised that you will need to run your code thru a transplier, like Babel.


Method definition shorthand

Method definitions in ES6 get a shorthand syntax.

ES5

var obj = {
    foo: function() {
        // code
    },
    bar: function() {
        // code
    }
}

ES6:

var obj = {
    foo() {
        // code
    },
    bar() {
        // code
    }
}

let and const

Block level scoping is now possible with let. In short, let is the new var. const (short for constant) is an immutable binding of a value. Utilizing an assignment operator, unary or postfix (– or ++) on a const variable throws and error.

How and where to use:

  • Use const for any value that will not change.
  • Use let to define a variable that can or will change.
  • Avoid using var in ES6.

Support

As of this writing, support for let and const is widespread in:

  • Chrome
  • Safari
  • Firefox
  • MS Edge

If you need to support Internet Explorer (any version), be advised that you will need to run your code thru a transplier, like Babel.


Modules

Modules make it easier to reuse blocks of code and import them in to your files. Very similar to javascript module loaders like AMD, CommonJS. Runtime behaviour defined by a host-defined default loader. Implicitly async model – no code executes until requested modules are available and processed.

// modules/math.js
export function square (x,y) {
    return x * y;
}

export var length = 5;
export var width = 6;


// app.js
import * from 'modules/math'
console.log(square(length, width))

Support

As of this writing, support for javascript modules is half implemented. import and export are supported in Chrome and Firefox, but no support exists for the actual loading of the files yet.


Template Strings (Template Literals)

Taking a page out of Mustache’s templating strings, ES6 allows you to finally do away with this:

var msg = 'Age: ' + age + ' | Name: ' + age;

and use this:

var msg = `Age: ${age} | Name: ${name}`;

Using backticks instead of quotes to open and close the string, and using the variables wrapped in parentheses preceded with a $ achieves the desired result.

Also of note, using this you can have a multiline string.

var msg = `Age: ${age}
| Name: ${name}
| DOB: ${dob}
| Address: ${address}
`;

Support

As of this writing, support for template strings pretty widespread. Of course, there is no support in IE, so if you need IE compatability, you will need to run your code thru a transplier, like Babel.


And finally, the one you should avoid:

Classes

ES6 introduces the Class keyword to Javascript. But before you go getting excited (or upset, depending upon your penchant for Object Oriented programming), there are a few things to consider.

First, is that Javascript is and still remains a prototypical language. Just because it now features the Class keyword doesn’t change that fact. Classes in ES6 are just syntactical sugar on top of the prototypical inheritance present in Javascript. As such, by using this syntactical sugar, you are pretending that Javascript operates in a way that it doesn’t. For some smaller instances, this nay be alright, but it can really confuse people who are just getting familiar with prototypical inheritance, and who might expect Javascript to act like a fully object oriented programming language, which it does not.

NodeJS 4.0

Node 4.0 has been released. This release is significant for a number of reasons, one of which is the merging of the NodeJS and the io.js projects in to one. The new Node (from version 4.0 and onward) will be based on the io.js repo. This should unify the Node project, which had seen some dissent in the ranks over the last year or so as some NodeJS contributors had moved over to the io.js project.

Of note, if you upgrade to v4.0 and run in to issues, you can always (and easily) roll back to prior versions.

For example, when I upgraded to v4.0, I got these errors when trying to run gulp:

~/Sites/zydelig-trivia-angular-frontend/node_modules/gulp-sass/node_modules/node-sass/lib/extensions.js:148
    throw new Error(['`libsass` bindings not found in ', binaryPath, '. Try reinstalling `node-sass`?'].join(''));
    ^
Error: `libsass` bindings not found in ~/Sites/my-awesome-project/node_modules/gulp-sass/node_modules/node-sass/vendor/darwin-x64-46/binding.node. Try reinstalling `node-sass`?
    at Object.sass.getBinaryPath (~/Sites/my-awesome-project/node_modules/gulp-sass/node_modules/node-sass/lib/extensions.js:148:11)
    at Object.<anonymous> (~/Sites/my-awesome-project/node_modules/gulp-sass/node_modules/node-sass/lib/index.js:16:36)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (~/Sites/my-awesome-project/node_modules/gulp-sass/index.js:163:21)
    at Module._compile (module.js:434:26)

Attempting to upgrade node-sass and gulp-sass had no effect on fixing it.

So, I had to roll back to v 0.12.7, the last release before the 4.0 merge. Thankfully, once I exhausted every other attempt to fix the issue, rolling back was easy.

In case you didn’t know, you can upgrade/downgrade Node itself thru npm. Here’s how:

sudo npm cache clean -f
sudo npm install -g n
sudo n 0.12.7

“n” is a helper package that allows you to upgrade/downgrade your node instance.

 

Take a big Gulp

Grunt vs Gulp - Fight!

Over the last few years, many of the projects I’ve worked on have been complex enough to warrant using a task runner to handle the process of compilation (in the case of Coffeescript, LESS and SASS files), concatenation and minification. Grunt emerged as the early favorite in this category because it was relatively easy to use and had a strong community backing.

But, as it always is with Javascript frameworks and toolsets, times change.

Now, Gulp.js has emerged as a competitor to Grunt. It’s designed for the same tasks as Grunt, but sports a few benefits.

The first that appealed to me was that with Gulp, you are writing your tasks in Javascript. Not JSON, but Javascript. This is a matter of preference I suppose, but I found writing my gulpfile out more descriptive than the JSON configuration files you use with Grunt.

Second, I like how in Gulp you can pipe, or chain your tasks together. As you are writing your tasks out, this mimics the workflow you’d like your files to be processed under, and it just makes sense from a coding perspective.

 gulp.task('galleryJs', function() {
 gulp.src(galleryJsSources)
 .pipe(concat('gallery.js'))
 // .pipe(uglify())
 .pipe(rename({suffix: '.min'}))
 .pipe(header(headerComment))
 .pipe(gulp.dest('assets/js/'));
 });

In the example above, the task ‘galleryJs’ takes the array of files with this name and passes it to the tasks concat (which concatenates all the files in to one), then that output is piped to uglify (minification), then the file is renamed (with the suffix ‘.min’ appended), then the header task is run (which prepends a timestamp to the file so you can easily see when it was generated – very helpful when trying to see if a minified file is updated or cached), and file it’s moved to the ‘assets/js’ directory with gulp.dest.

Third, and my favorite, is that with the –save-dev argument, Gulp will save the packages used in your gulpfile to a node_modules directory, meaning (assuming you are checking this in to Git) that the next person who checks out your branch won’t have to manually download these packages for Gulp to work. I’m not sure if this was possible with Grunt, but it seemed like every project I ever used Grunt on required the user first to make sure they had all the packages Grunt was referencing in the gruntfile.

Speed between the two task runners seems about the same. I find that I can write tasks quicker in Gulp, so overall the process of using Gulp seems quicker, at least for me.

The one area where Grunt still reigns supreme is in the sheer number of packages available for it (compared to Gulp). Gulp is gaining a lot of traction, but Grunt still has more packages available for it, for now.

Brackets

Meet Adobe Brackets

When it comes to text editors, I’m a bit fickle. I’ve used just about every one available to me on the Mac platform over the last 10 years. They all have their pros and cons. The ones I generally keep coming back to again and again are TextMate, Coda and Sublime Text.

All three have their strengths…

TextMate 2TextMate: Though most of the TextMate community has moved on to Sublime Text, TextMate still offers a great editor with a wide range of syntax support. It’s a Mac native app and behaves appropriately when interacting with the file system and uses standard Cocoa supported features like drag and drop. Version 2 is still yet to be officially ‘released’ as a finished product (it’s currently in beta after 4 years publicly available as an alpha build). But TextMate is still a competent code editor, and because I’ve used it for so long, I continually return to it every few months. Still, it saddens me that an app that had the potential to rule the roost has fallen by the wayside mainly because of developer apathy. TextMate 2 is open sourced now (although the final product will be a commercial product), and development seems to have picked up over the last couple of years as the project heads towards a

Coda by PanicCoda: Coda has a bit of everything in it (code editor, SQL query tool, reference materials, terminal), yet (and it pains me to say this) it has the weakest editor of the bunch. Version 2.0 (and 2.5 and later versions) make big improvements to the editor, but it still doesn’t compare with Sublime Text or TextMate in this area. It’s also not the leanest of applications, and stability has been an issue, at times (though currently it’s been running rock solid for me for the last couple of months). But, if I’m building HTML/CSS, I find Coda the better tool than the other two editors. Its support for CSS3 features/autocompletion comes in handy in this context.

Sublime TextSublime Text: Sublime Text has risen from an upstart leeching off of TextMate’s awesome bundle architecture to become the 800lb gorilla in the text editor space. It’s a cross platform app, which is either a blessing (if you need to work on Windows or Linux) or a curse (if you value a native file tree and drag and drop features from the Finder). But the power of Sublime lies in its thousands of Packages and it’s 3rd party (but uber easy to install) Package Control system. Think of Sublime Text as a race car body and engine. Now think of Package Control as every other accessory you would want to add to that race car to do what you want it to do.

So over the last couple of years, I’ve flipped and flopped between all three of the above tools depending upon what project I’m working on. But a few months ago I downloaded Brackets.

Brackets is an open source editor built on the power of Node.js. As such, Brackets is built using Javascript/HTML/CSS. So it’s cross platform, but it’s built using the language of the web. It’s highly extensible and new extensions can be written in Javascript. Like Sublime Text, it has a Package (nee Extension) system that allows you to easily tailor the tool to your needs. The community behind Brackets is active and has grown significantly in just the last 6 months that I’ve been following the project.

Brackets by AdobeBeing built on Javascript, I was concerned that performance would be horrible. To put that to a test, I opened a JSON file that was part of the Swimsuit 2015 project I worked on. This file is 6885 lines of code uncompressed and 270kb. All of the editors can open the file alright. However, converting the compressed output to beautified JSON isn’t possible in TextMate (using an iMac Retina 2015 with 32GB of RAM). Sublime Text handles the file just fine. Coda can open it, but it takes a good while to beautify (using the PHP Toolkit plugins ‘JS Tidy’ command).

I was sure Brackets would choke on this file, but Brackets opens it and pretty prints it just as easily as Sublime Text. Score one for the upstart built on web standards.

Other great features of Brackets is split window editing, built in preprocessor support for SASS and LESS, inline editing of CSS (command-E on a highlighted ID or class in your code and Brackets will open the corresponding CSS and allow you to edit in inline in your document).

Brackets - Inline CSS Editing

I find myself using Brackets more and more, and becoming enamored with it’s capabilities. My only complaints are that, like Sublime Text, it is not a native app, and it’s user interface leaves a lot to be desired. There are many Extensions that skin the UI, but I’ve yet to find one that knocks my socks off. Still, as an editor, Brackets is great, open source, free, and extremely flexible and capable.

Update: And after writing this post, I discovered Atom. Atom is built in the style of Brackets – using HTML/CSS and JavaScript running on Node. Atom is open sourced and backed by Github. It also has a large library of extensions and themes. It lacks the Photoshop integration that Brackets offers, but seems to be a very active project with lots of commits. If you like Brackets you should give Atom a look. 

Moving On

Moving On

After nearly 4 years at Sports Illustrated (first via Turner and then via Time Inc.), I have moved on.

I met some of the smartest and nicest people I’ve ever worked with while working for both Turner and Time Inc. on the Sports Illustrated project. I learned lots of valuable information on how super high traffic sites are built and hosted. It was a huge departure from the earlier places I worked, where you never really had to consider what happened to your site when 5,000,000 people visit in just a few hours.

While with SI at Turner, I managed one of the finest teams of web developers ever assembled. When I shifted to Time Inc., my title and focus changed and I was back in the trenches writing code again. Fun projects like Swimsuit 2014 were exhausting, but gratifying. Other projects, like the SI relaunch on Drupal were opportunities to learn a new platform (though not nearly quite as fun) and expand my skill set.

Working on Sports Illustrated was a tough gig. The sports world doesn’t keep 9-5/M-F hours, and as such, you often find yourself on call during nights and weekends. That sort of expectation to be ‘on’ takes it’s toll on you, and eventually, you look for things to do that aren’t quite as demanding.

I’ll always value the time I had at SI and the people I worked with, above all else.

As for where I’ve landed… I’m the new Manager of Digital Engineering for Re/Code.