Quick and dirty look at ECMAScript 6

March 17, 2016 by JavaScript   ES6  

Just to get everyone up to speed, what is ECMAScript exactly?

ECMAScript (ES) is the standardized scripting language specification most popularly implemented by JavaScript (and a few others) 

In this post I am going to give you a quick overview of the JavaScript implementation of the 6th major release of this specification (just enough information to get you fired).

Now, shall we begin?

Shall We Begin

  • Remember to "use strict" mode when using ES6 functionality.
  • Be sure to look at the browser compatibility table as seen over here before using any of this functionality.

Block Scope

Traditionally JavaScript makes use of function-level scoping, which employs "hoisting" (leads to all kinds of funny issues). The ES6 spec proposed the use of block scoping as an alternative.

  • Variables

    for (let i = 0; i < 2; i++) {
    	console.log(i);
    }
    console.log(i);

    The let keyword was introduced, limiting the use of the declared variable to the statement block or expression it is used in.

    In the snippet above we are unable (undefined error) to write variable i to the console, since it is only available to its statement block (its for loop).

  • Functions

    function a() { console.log('a'); }
    	
    { // block scope
    	function b() { console.log('b'); }
    	a();
    }
    
    b();

    If you've ever worked in languages like C# or Java, you will recognise this as anonymous blocks.

    Basically everything inside the anonymous block, cannot be accessed from outside the block, so the snippet above will fail to call function b (since its outside its scope).


Arrow functions

An arrow function is basically an anonymous function (similar to function expressions), the arrow body can either be an expression or statement.

var a = [1, 2, 3];

// arrow statement body a.forEach(v => { console.log(v); });
// arrow expression body var b = a.map(v => v * 2); console.log(b);

It is however different to a function expression in that it makes use of its parent scope instead, have a look at the example below.

function a(c) {
	this.name = 'test';
	c.apply(this);
}
new a(c => { console.log(this); });
new a(function() { console.log(this); });

The arrow function in the snippet above will write the Window object to the console (that being its lexical scope), using the apply function has no effect on its scope, while the function expression now lives in the scope of its parent object.

So take care if you're thinking about substituting your function expressions for arrow functions.

Extended parameters

  • Default Parameters

    function A(P, R, t = 5) {
    	return P * (1 + ((R / 100) * t));
    }

    Very straightforward, we simply assign a default value (t=5) thereby making the argument optional, exactly the same as in PHP, C# etc..


  • Rest Parameters

    function Z(M, ...v) {
    	let sum = v.reduce((a, b) => a + b );
    	return M * sum;
    }

    Similar to the params keyword in C# and most likely borrowed from varargs in Java, it deals with an indeterminate number of objects as an array. In the snippet above all arguments passed to the function after the M variable will be accessible in the v variable.


  • Spread Operator

    var set1 = [1, 2, 3];
    var set2 = [...set1, 4, 5, 6];
    var x = [1, 2, 3];
    function a(a, b, c) { console.log(arguments); } a(...x);

    Very useful operator, it expands the set of values passed to it into its surrounding expression, e.g. in the snippet above we concat set1 with the values of set2. It also gives us a nicer alternative to the apply function, instead of calling a.apply(x) we spread the array into the arguments of a, e.g. a(...x).

Object Literal Property Value Shorthand

var x = 1, y = 2;
var coord = { x, y };

When working with Object notation, I quite often find that I have to repeat variable name+assignments e.g. { x: x, y: y}, this feels quite dirty and ugly on the eye, the new shorthand expression cleans it up a bit.


${Template Literals}

var user = {
	firstName : 'Christoff',
	lastName : 'Truter',
	age : function(birthday = new Date(1983, 2, 2)) {
		var ageDate = new Date(Date.now() - birthday.getTime());
		return Math.abs(ageDate.getUTCFullYear() - 1970);
	}
};

var text = `The name is ${user.lastName}, 
			${user.firstName} ${user.lastName}, 
			I am ${user.age()} years old`;

Note: Template literals are enclosed by the back-tick (` `).
Ever since I wrote my first bit of JavaScript (back in 1998), concatenating strings, formatting values, substrings etc, proved to be quite an ugly pain in the neck. But no more, with the introduction of template literals that will be a thing of the past.

Like seen in the snippet above, a template may stretch over multiple lines, contain expressions etc, very useful.

Classes

class Maps {
	constructor(name) {
		this._name = name;
		console.log(name);
	}
	
	set name  (value) { this._name = value; }
	get name  () { return this._name; }
	
	static latLng() {
		console.log('LatLng');
	}
}

class Google extends Maps {
	constructor() {
		super('Google');
	}
}


I think the addition of classes (with all the goodies like inheritance, constructors, properties, static methods) into JavaScript is long overdue, we've been faking classes for years ;), the guy in the video clip below is clearly a well seasoned JavaScript developer.


Other

Other new features you might want to look into - generator functions, the iterator protocol, promises, modules
(export / import)
, new regular expression features, just to name a few.

On a side note, if by a slim chance you have read my "Quick and dirty look at TypeScript" post, you will notice quite a number of similarities between TypeScript and the ES6 spec, some even go as far as calling TypeScript a preview of ES6  (TypeScript is after all a subset of the ES specifications, but with sexy static typing added to the equation), giving us the ability to use ES6 today.

Not like this post is purely propaganda for TypeScript....


Leave a Comment



Related Posts

Quick and dirty look at TypeScript

January 29, 2015