What New ES6/7 Has To Offer?

This post will give you a quick introduction to ES6 (aka ECMAScript 2015). If you don't know what is ES6, it’s a new JavaScript implementation. If you haven't taken a look at ES6/7 yet you're missing out on some amazing advances to the JavaScript language.

Some of the important features of ES6/7 are below:
• let, const
• Template Strings/literals
• Arrow Functions
• Classes
• Destructuring
• Modules
• Native Promises
• Async Await
• Spread Operators
• Rest Parameters

Let + Const
In ES5, you declare variables via var. Such variables are function-scoped, their scopes are the innermost enclosing functions. In ES6, you can additionally declare variables via let and const. Such variables are block-scoped, their scopes are the innermost enclosing blocks.

let is the new var and block-scoped: they only exist in the block they are defined in.
var num = 0; //globally scoped

for (let i = 0; i < 10; i++) { //i is block scoped
  num += i;
  console.log('value of i in block: ' + i);
}

console.log('Is i defined here?: ' + (typeof i !== 'undefined')); //Is i defined here?: false 

Constants (also known as "immutable variables"), i.e., variables which cannot be re-assigned new content. const is single-assignment. const works like let, but the variable you declare must be immediately initialized, with a value that can’t be changed afterwards.
const foo;
    // SyntaxError: missing = in const declaration

const bar = 123;
bar = 456;
    // TypeError: `bar` is read-only

Template Strings/literals
Template literals are a new feature in ES6 to make working with strings and string templates easier. Template strings provide syntactic sugar for constructing strings. You wrap your text in `backticks` and you'll get the features described below.
• They can be multi-line. Finally!
• You can interpolate variables in them
• You can actually interpolate using any kind of expression, not just variables
• You can construct raw templates that don't interpret backslashes
// Basic literal string creation
`This is a pretty little template string.`

// Multiline strings
`In ES5 this is
 not legal.`

// Interpolate variable bindings
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Unescaped template strings
String.raw`In ES5 "\n" is a line-feed.`

var today = new Date()
var text = `the time and date is ${today.toLocaleString()}`
console.log(text)
// <- 'the time and date is 8/26/2015, 3:15:20 PM'



Arrow functions
Fat arrow functions, also known as just arrow functions are a brand new feature in ECMAScript 2015 (formerly ES6). Arrows are a function shorthand using the => syntax. Arrow functions serve two main purposes: more concise syntax and sharing lexical this with the parent scope. Arrow functions behave differently than traditional JavaScript functions in a number of important ways:
• Lexical this binding – The value of this inside of the function is determined by where the arrow function is defined not where it is used.
• Not newable – Arrow functions cannot be used a constructors and will throw an error when used with new.
• Can’t change this – The value of this inside of the function can’t be changed, it remains the same value throughout the entire lifecycle of the function.
var reflect = value => value;

// effectively equivalent to:

var reflect = function(value) {
    return value;
};
When there is only one argument for an arrow function, that one argument can be used directly without any further syntax. The arrow comes next and the expression to the right of the arrow is evaluated and returned. Even though there is no explicit return statement, this arrow function will return the first argument that is passed in.

If you are passing in more than one argument, then you must include parentheses around those arguments. For example:

var sum = (num1, num2) => num1 + num2;

// effectively equivalent to:

var sum = function(num1, num2) {
    return num1 + num2;
};

The sum() function simply adds two arguments together and returns the result. The only difference is that the arguments are enclosed in parentheses with a comma separating them (same as traditional functions).

When you want to provide a more traditional function body, perhaps consisting of more than one expression, then you need to wrap the function body in braces and explicitly define a return value, such as:
var sum = (num1, num2) => { return num1 + num2; }

// effectively equivalent to:

var sum = function(num1, num2) {
    return num1 + num2;
};
You can more or less treat the inside of the curly braces as the same as in a traditional function with the exception that arguments is not available.

Because curly braces are used to denote the function’s body, an arrow function that wants to return an object literal outside of a function body must wrap the literal in parentheses. For example:
var getTempItem = id => ({ id: id, name: "Temp" });

// effectively equivalent to:

var getTempItem = function(id) {

    return {
        id: id,
        name: "Temp"
    };
};
The concise syntax for arrow functions also makes them ideal as arguments to other functions. For example, if you want to sort an array using a custom comparator in ES5, you typically write something like this:
var result = values.sort(function(a, b) {
    return a - b;
});
That’s a lot of syntax for a very simple procedure. Compare that to the more terse arrow function version:
var result = values.sort((a, b) => a - b);
The array methods that accept callback functions such as sort(), map(), and reduce() all can benefit from simpler syntax with arrow functions to change what would appear to be more complex processes into simpler code.

Classes
ES6 Classes formalize the common JavaScript pattern of simulating class-like inheritance hierarchies using functions and prototypes. They are effectively simple sugaring over prototype-based OO, offering a convenient declarative form for class patterns which encourage interoperability. Classes support prototype-based inheritance, constructors, super calls, instance and static methods.
class someClass {
    constructor(name, age) {
        this.name = name;
        this.age = age;
 }

    sayName() {
        alert(this.name);
    }

    sayAge() {
        alert(this.age);
    }
}

var myInstance = new someClass('dwayne', 27);
myInstance.sayName();
Class inheritance
class Child extends someClass {
    constructor(name, age) {
        super(name, age);
    }
    
    // Override the someClass method above
    sayName() {
        // This will call someClass.sayName() triggering the old alert
        // Which will just display our name
        super.sayName();
        
        // This will trigger the new alert which has labels and our age
        alert('Name:' + this.name + ' Age:' + this.age);
    }
}

var myChild = new Child('dwayne', 27);
myChild.sayName();
As you can see, classes are extremely flexible especially when extending a base class and having the ability to easily override a parent method without needing to write any boilerplate logic to do so.
In the ES6 classes syntax we have access to a function called super() which essentially just calls the parent function depending on the context and then returns the result. Calling super.parentMethodName() from within a child class will call the base class you inherited.

Destructuring
Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment).

/*Destructuring objects*/
const obj = { first: 'Jane', last: 'Doe' };
const {first: f, last: l} = obj;
    // f = 'Jane'; l = 'Doe'

// {prop} is short for {prop: prop}
const {first, last} = obj;
    // first = 'Jane'; last = 'Doe'


/*Array destructuring*/
const iterable = ['a', 'b'];
const [x, y] = iterable;
    // x = 'a'; y = 'b'


// list matching
var [a, ,b] = [1,2,3];
a === 1;
b === 3;

Modules
ES6 is the first time that JavaScript has built-in modules. In ES6 each module is defined in its own file. The functions or variables defined in a module are not visible outside unless you explicitly export them. This means that you can write code in your module and only export those values which should be accessed by other parts of your app.

ES6 modules are declarative in nature. To export certain variables from a module you just use the keyword export. Similarly, to consume the exported variables in a different module you use import.

Let's create a simple module that has two utility functions:
1. generateRandom() : Generates a random number.
2. sum() : Adds two numbers.

Next, let's create a file named utility.js for the module:
//utility.js

 function generateRandom() {
    return Math.random();
 }

 function sum(a, b) {
    return a + b;
 }

 export { generateRandom, sum }
That's it! The export keyword on the last line exports the two functions. As you can see, the exported functions are listed in curly braces separated by a comma. You can also rename the values while exporting like this:
 export {generateRandom as random, sum as doSum}

Now, let’s see how to consume the exported values in a different module.
//app.js

 import { generateRandom, sum } from 'utility';

 console.log(generateRandom()); //logs a random number
 console.log(sum(1, 2)); //3
Note the first line. This imports the exported values from the module utility. If you want to import a single value (for example sum), you can do it by writing the following:
import { sum } from 'utility';

You can also import the entire module as an object and access exported values as properties. So, we can modify our code as following:
 import 'utility' as utils;

 console.log(utils.generateRandom()); //logs a random number
 console.log(utils.sum(1, 2)); //3
Rest of the topics are coming soon.

References: Understanding ECMAScript 6 arrow functions
Learn ES2015
http://exploringjs.com/es6/index.html
ES6 Template Literals in Depth
Understanding ES6 Modules

Comments

Popular Posts