JavaScript: The New Parts


ES6/ES7


By @rjanardan

About Me

  • Open Source Enthusiast
  • love.js
  • Author & Speaker
  • Working @ Hewlett Packard Enterprise

Audience

  • Frontend/JavaScript programmers


Objective

  • Catup on new features
  • Not just syntax

Agenda

  • About ECMAScript 2015
  • New Features
  • Environments Support

Standards Body

About ECMAScript 2015

  • ECMAScript.next
  • ECMAScript harmony
  • ES6
  • ECMAScript 2015

Goals

  • Complex applications
  • Libraries and frameworks
  • Code generators

Themes

Programmer conveniences

Reduce need for additional libraries

For library builders

High-level language features

Low level language features

Better readability and maintainability

Performance optimization

Functional programming

Object-oriented programming

Programmer conveniences

arrow functions, array functions, string functions, for..of, function parameters, parameters with default values, variable parameters, destructuring, template strings

Reduce need for additional libraries

Math library, new data structures - Maps, Sets, WeakMaps, WeakSets

Examples

var hasB = "ecmascript".indexOf('p') > -1; alert(hasB);

Presentation template from John K Paul @johnkpaul

String APIs - Examples


String.raw``

String.prototype.repeat()

String.prototype.startWith()

String.prototype.endsWith()
		  
let a = [10, 20, 30, 40, 50]; alert(a.find(x => x > 30)); a.fill(44); alert(a);

template strings

var first = "John K." var last = "Paul"; var t = `I'm ${first} ${last}!`; alert(t);

Arrow function - Example


//Without arrow function

var std = function std(yr) {

  return "ECMAScript" + yr;

};


//With arrow functions

var std = yr => "ECMAScript"+yr;


//Return an object

let makept = (a, b) => ({ x:a, y:b});

		  

Object Literals



0b111 // 7 (decimal)
              
0b11+0o11 // 12 (3+9)
		  

Scope - let


for (let i = 0; i < 3; i++) {

  console.log('iterator ' + i);

}

console.log('iterator ' + i++); // error

		  

Scope - const


const version = 6;

console.log(version);

version = 7; // error
		  

Scope - const (block scope)


{

const version = 6;

console.log(version);

}

version = 7; // error

		  

Enhanced Object literals

Properties Shorthand notation



let firstname = "Janardan",
    
  lastname = "Revuru",

  organization = "HPE EG India R&D";




let employee = {                       let employee = {
                                      
  firstname: firstname,                   firstname,
                                      
  lastname: lastname,                     lastname,
                                      
  organization: organization              organization
                                      
};                                    };
                                         (new notation)

Shorthand notation (extension)

          
let employee = {

    firstname,

    lastname,

    org: organization,

    location: "Mahadevapura"

};  

Method shorthand

          
let payroll = {

  _employees: [],

       print() {                       

        console.log(JSON.stringify(employee));

      }
};

payroll.print();

Computed Property keys


let i = 0;
              
let std = "ecma";

let fn = "print";

let obj = {

  ["js" + ++i]: i,

  ["js" + "2"]: ++i, 

  ["js" + new Date().getFullYear()]: 10,

  [std]: 20,

  [fn]: function() { console.log("hello!"); },

};

          

Number object extensions

          
 Number.isFinite(3); // true

 Number.isFinite('3'); // false

 isFinite('3'); // true

 Number.EPSILON

 (0.21+0.2) !== (0.41)

 Number.MIN_SAFE_INTEGER

 Number.MAX_SAFE_INTEGER

 Number.isSafeInteger()

Default Parameters

          
function fn(one, two, three) {

  console.log(one, two, three);

}

fn(1);

Default params (2)

          
function simple_interest(p, t, r) {

  let time = t || 1;

  let rate = r || 8;

  let si = (p * time * rate)/100;

  console.log("p =" + p + ", t = "+ time + 

      ", r = "+rate + "; si = " + si);
}

simple_interest(1000, 5);

simple_interest(1000, 2, undefined);

simple_interest(1000, 2, null);

simple_interest(1000, 2, 0);

ECMAScript Process Stages

NoStagePurpose
0StrawmanInput into specification
1ProposalCommittee is considering it. Identify value, solution, potential challenges
2DraftDescribe syntax, semantics and formal spec language
3CandidateRefine based on implementators and users
4FinishedReady for inclusion in coming version


The TC39 Process

ES2016/ES7

Array.prototype.includes()

Exponentiation operator

Upcoming features

SIMD.js

Async functions

Object.values/Object.entries

String padding

Object.getOwnPropertyDescriptors

Rest parameters

          
function add(...nums) {

  var result = 0;

  nums.forEach(function (num) {

  result += num;

  });

  return result;

}

add(10, 20, 30, 50);

Number object extensions

          
function max(a, b, c) {

    // code to find max of three numbers

}

let a = [10, 20, 30];

max(...a); // = max(10, 20, 30)

let b = [...a, 40, 50];

for..of iterator

          
 let arr = ["mon", "tue", "wed"];

 for (let i in arr) {

    console.log(i); //prints index

 }

 for (let i of arr) {

     console.log(i); //prints values

 }

 for (let [i,v] of arr.entries()) {

   console.log(i, ": ", v); // prints index, values

}

Destructuring

          
const distro = {

  name: 'Linux Mint',

  os_type: 'linux',

  based_on: ['debian', 'ubuntu'],

  origin: 'Ireland',

  arch: ['i386', 'x86_64'],

  popularity: 1

};

let { name: name, origin: origin } = distro;

Destructuring Array

  
let today = new Date();

let UTCstring = today.toUTCString();

let [, date, month, year] =    
           today.toUTCString().split(" ");

Destructuring (2d array)

  
let matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]];

let [[a11,,],[,a22,],[,,a33]] = matrix;

// swapping elements
let [a, b] = [1, 2];

[a, b] = [b, a];

Destructuring (iterator)

  
const books = [

  { t: "Eloquent JavaScript",

    a: "Marijn"

  },

  { t: "Exploring ES6",

    a: "Alex"

  }];  

for (let {t} of books) { 

  console.log(t);

}

Destructuring (fn params)

  
function get_rank({popularity: p}) {

	return p;

}

const distro = {

  name: 'Linux Mint',

  os_type: 'linux',

  popularity: 1

};

get_rank(distro);

Built-in data structures

Maps
Sets
Weakmaps
Weaksets
let set = new Set(); set.add('a'); set.add('b'); set.add('c'); set.add('b'); alert(set.size); set.forEach(alert);
var obj = {'key': 'val'}; var map = new Map(); map.set('key', 'val'); alert('key' in obj); alert(map.has('key'));

Much more...

Math APIs
Object APIs
RegEx APIs
Template literals
Iterators
Generators
Promises
Tail calls
Typed Arrays
Unicode
...
...
__proto__
Module Loaders
Proxies
Reflect API
Subclassable built-ins
Symbols
var p = new Promise( function(resolve, reject){ setTimeout(resolve, 1000); } ); p.then(function(){ alert('after 1 second'); });
var obj = {key: 'val'}; var obj2 = {key2: 'val2'}; var merged = Object.assign(obj, obj2); alert(merged.key); alert(merged.key2);
class Greeter { constructor(message) { this.message = message; } greet() { alert(this.message) } } var greeter = new Greeter('Hey'); greeter.greet();

ES6 Support

Environment Support
Microsoft Edge 13 84%
Google Chrome 46 74%
Mozilla Firefox 44 74%
Node 5.0 59%
Babel 71%
Traceur 59%
Safari 54%
Node 4.0 53%

http://kangax.github.io/compat-table/es6/

What you should do

  • Try online at es6fiddle.net
  • Read the series in OSFY Magazine
  • Follow TC39, contribute to ES8
  • Learn from Babel ES6 to ES5
  • Read Axel Rauschmayer
  • Add a branch with an ES6 transpiler
  • Learn about asm.js and WebAssembly @brendaneich

Thank You

Questions?

By @rjanardan

8050780608

Janardan Revuru


@rjanardan

janardan.revuru@gmail.com

More examples

  • Destructuring
  • Rest parameters
  • Promises
  • Template strings
  • Classes
  • Generators

CopyScript

  • CoffeeScript - arrow functions
  • Python - Generators
  • Lisp - Destructuring
  • C - const/block scope
  • E - template strings
var n = [1, 2, 3, 4] .find(x => Object.is(x, 3)); alert(n);

destructuring

var arr = [1, 2, 3]; func(arr); function func([fst, snd, thd]){ alert(fst); alert(thd); }

destructuring/rest params

function destructure(...args){ var [options, callback] = args; alert(options.v); alert(typeof callback); } var o = {v: true} destructure(o, () => 1);
function* inf(){ var i = 0; while(true){ yield ++i; } } for(var x of inf()){ alert(x); if(x > 3) { break; } }

Try It Out

es6-shim by Paul Miller

  • String.prototype.contains()
  • Promise()
  • Set()
  • Map()
  • Array.from()
  • Number.isNaN()
  • Object.is()
  • String.prototype.codePointAt()