Monday, February 13, 2017

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
• Object Destructuring
• Concise Objects
• Modules
• Default Parameters
• 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()}`
// <- '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.

Rest of the topics are coming soon.

References: Understanding ECMAScript 6 arrow functions
Learn ES2015
ES6 Template Literals in Depth

No comments:

Post a Comment