Whats New in ES6 – http://bit.ly/1cVf9bJ – interested reources found later



Whats New in ES6 – http://bit.ly/1cVf9bJ – interested reources found later

1 1


ES6

Talk about What's New in EcmaScript 6. Initially preparing for JS Chicago October 2013

On Github khan4019 / ES6

Whats New in ES6

http://bit.ly/1cVf9bJ

MD Khan / @mdkhan005

Quiz

How to comfort a JavaScript bug?

console it

Why do C# and Java developers keep breaking their keyboards?

They are strongly typed

Elijah Manor

June 1997

June 1998

December 1999

Abandoned

December 2009

December 2014

already started ES7?

It's coming?

Things can and might change

ES6: draft

JavaScript: Language

ECMAScript: Standard

Goals

  • Complex Application
  • Libraries
  • Code Generation
Harmony: goals

Honest Goals

Steal from Libraries

Make you Lazy

Reduce your Paycheck

Defaults

Parameter

 function foo(a, b)
 {
   a = typeof a !== 'undefined' ? a : 42;
   b = typeof b !== 'undefined' ? b : 'default_b';

   console.log('a = '+a);
   console.log('b = '+b);
 }									
							
foo(); //a = 42, b = 'deafult_b'

foo(3); //a = 3, b = 'deafult_b'

foo(3,'newBee'); //a = 3, b = 'newBee'
							
 function foo(a, b)
 {
   a = a || 42;
   b = b || 'default_b';
   console.log('a = '+a);
   console.log('b = '+b);
 }
								
foo(); //a = 42, b = 'deafult_b'
foo(3); //a = 3, b = 'deafult_b'
foo(3,'newBee'); //a = 3, b = 'newBee'
								

ES6

 function foo(a=42, b='default_b')
 {
   console.log('a = '+a);
   console.log('b = '+b);
 }								
							
foo(); //a = 42, b = 'deafult_b'
foo(3); //a = 3, b = 'deafult_b'
foo(3,'newBee'); //a = 3, b = 'newBee'
								
ES6: default value Firefox: default Parameters

Object

Property shorthand

var myShortObj = {x, y};

console.log(myShortObj);

// myShortObj ={x:x, y:y};
							

Function Scope

JS Function Scope

function justLooping() {
  for (var i = 0; i < 5; i++) {
     console.log('for nothing');
 } 
}
justLooping();
							
function justLooping() {
  for (var i = 0; i < 5; i++) {
     console.log('for nothing');
 }
 console.log(i); //i=5
}
justLooping();
							

Hoisting is bad for encapsulation

function justLooping() {
  console.log(i); //i=undefined 
  for (var i = 0; i < 5; i++) {
     console.log('for nothing');
 }
 console.log(i); //i=5
}
justLooping();
							

let is the solution

function justLooping() {
//i not here. Reference Error
  for (let i = 0; i < 5; i++) {
     console.log('for nothing');
 } 
 //i not here. Reference Error
}
justLooping();
							
function justLooping() {
//i not here. Reference Error
  for (let i = 0; i < 5; i++) {
     var mySquare = i*i;
 } 
 //i not here. Reference Error
 console.log(mySquare); // ReferenceError: 
}
justLooping();									
								

const

Initialized once, can never be modified

defs.js

defs.js

... prefix

rest parameters

function foo(a, b, c, ...others){
	return others;
}

foo(1,2,3,4,5,6);//[4,5,6];

foo(1,2,3);//[];
foo();//[];
							
MDN: arguments

spread

let a = [0, 1, 2];
let [x, ...xs] = a;
// x = 0
// xs = [1, 2]				
[y, ...ys = [0]; // y = 0, ys = []
[z, ...zs] = []; // z = undefined, zs = []
							
Spec: Spread

Arrow Function

=>

var square = function(a) {
    return a * b;
};

							
var square = a => a*a;
							
var add = function(a, b) {
    return a + b;
};

//with ES6
var add = (a, b) => a+b;
							
Harmony: Arrow Function
var sum = function() {
    return 1 + 2;
};

//ES 6
var sum = () => 1 + 2;
							

multi line in the expression

//change this for beter understanding
let fives = [];
nats.forEach(v => { if (v % 5 === 0) fives.push(v); });
							

return object

var myObj = id => ({Id: id});
							
var getTempUser = function(id) {

    return {
        id: id,
        name: "Temp"
    };
};							

//ES 6
var getTempUser = id => ({ id: id, name: "Temp" });
							
Nicholas Zakas: ES6 Arrow Function

What the heck is this!!

function MyClickHandler {
	var that = this;
	//var self = this;

	var elem = document.getElementById('myDiv');
	
	elem.addEventListener('click', function () {
		  console.log('CLICK');
		  that.handleClick();
	});
}

MyClickHandler.prototype.handleClick = function () { ... };
							

lexical this, no more that = this

//from Harmony: make it better
// ''=>'' has only lexical ''this'', no dynamic ''this''
const obj = {
  method: function () {
    return () => this;
  }
};
							

Class

function Friend(name, city){
	
  this.name = name;
  this.city = city;
}

Friend.prototype.toString = function(){
  return '('+this.name+':'+this.city+')';
}	
							
spec: Class Classes in ES6
class Friend{

  constructor(name, city){
	this.name = name;
      this.city = city;
  }

  toString(){
	return '('+this.name+':'+this.city+')';
  }
}
							
Harmony: Class

sub-type

function DevFriend(name, city, favLang){
	Friend.call(this, name, city);
	this.favLang = favLang;	
}

DevFriend.prototype = Object.create(Friend.prototype);

DevFriend.prototype.constructor = DevFriend;

DevFriend.prototype.toString = function(){
  return this.favLang + ' '+ Friend.prototype.toString.call(this);
}	

							
Axel R.: Fluent slides

ES6: sub-type

class DevFriend extends Friend {
  
  constructor(name, city, favLang) {
	//same super.constructor(name, city)
	super(name, city); 
	this.favLang = favLang;
  }
  
  toString() {
	return this.favLang+' '+super();
  }
}	

							

ES6: static

class Friend {
  
  static stupidFriend() {
	return new Friend('Stupid', 'Chicago');
  }
  
  constructor(name, city) {
	this.name = name;
	this.city = city;
  }

}

var bss = Friend.stupidFriend();

							

Named Parameter


function foo(arg0, { opt1, opt2 }) {
	return [opt1, opt2];
}


foo(0, { opt1: 'a', opt2: 'b' });
//['a', 'b']
								
							

Destrcturing

var obj = {first:'Java', last:'Script'};

let { first:f, last:l } = obj;

console.log( f +' '+ l); //Java Script
							
  • Variable Declaration
  • Assignment
  • Parameter Definition

Arrays

let [ x, y ] = ['a', 'b'];

let [ x, y, ...rest ] = ['a', 'b', 'c','d'];

//x='a', y='b', rest=['c','d']

[ x, y] = [y, x]; //swap
							

Refutable(default)

//Refutable (default)

var obj = {a:x, b:y} = {a:3}; //fails
							

Irrefutable

//Irrefutable (default)

var obj = {a:x, ?b:y} = {a:3}; //x=3, y = undefined
							

Default Value

//refutable (default)

var obj = {a:x, b:y=5} = {a:3}; //x=3, y=5

							

Module

similar to Node.js module

  • Rename imports
  • concatenations
  • Automatic linting
  • conditional module loading
harmony: Module

Declare Inline

module "foo" {
    export let x = 42;
}
							

External module load

import { y } from "foo";
							

//If a module defines a default export
//then import default export by omitting the curly braces

module "foo" {
    export default function() { console.log("hello!") }
}

import foo from "foo";
foo(); // hello!
							
harmony: Module

Symbol

let sym = Symbol();

console.log(typeof sym); // symbol
							

Each Symbol is unique and immutable

either undefined or a String value

ES5: Symbol

Symbol for Enum

let red = Symbol();
let green = Symbol();
let blue = Symbol();
function handleColor(color) {
	switch(color) {
		case red:
			...
		case green:
			...
		case blue:
			...
	}
}								
							
Copied from slides of Axel Rauschmayer

Symbol as Property Key

let specialMethod = Symbol();
let obj = {
	// computed property key
		[specialMethod]: function (arg) {
			...
	}
};
	obj[specialMethod](123);
	Shorter – method definition syntax:
		let obj = {
			[specialMethod](arg) {
				...
		}
};								
							
Copied from slides of Axel Rauschmayer

Others

Template

templateHandler 'Hello ${first} ${last}!'

templateHandler(['Hello ', ' ', '!'], first, last)
							

Harmony template

Maps

let map = new Map();
let obj = {};

map.set(obj, 123);

console.log(map.get(obj)); // 123
console.log(map.has(obj)); // true

map.delete(obj);
console.log(map.has(obj)); // false
							
MDN: Map Map and Set

Sets

A collection of values without duplicates.

let set1 = new Set();
set1.add('hello');
console.log(set1.has('hello')); // true
console.log(set1.has('world')); // false
let set2 = new Set([3,2,1,3,2,3]);
console.log(set2.values()); // 1,2,3
							
MDN: set
var items = new Set();
items.add(5);
items.add("5");
items.add(5);     // oops, duplicate - this is ignored

console.log(items.size());    // 2
							
Nicholas: Sets

Generator and Iterator

yield

haromony: yield

From Python

yeild = resumable return

yield generator

Implement Iterator

function createArrayIterator(arr) {
    let index = 0;
    return {
        next() {
            if (index < arr.length) {
                return { done: false, value: arr[index++] };
            } else {
                return { done: true };
            }
        }
    }
}
							
MDN: generator and Iterator

Generator

function* generatorFunction() {
    yield 1;
    yield 2;
}

let genObj = generatorFunction();
genObj.next()
//{ done: false, value: 1 }
genObj.next()
//{ done: false, value: 2 }
genObj.next()
//{ done: true }

							
2ality: Iterators-generators

for in loop

var planets = ["Hello", "Java", "Script", "Devs"];

for (p in planets) {
  console.log(p); // 0,1,2,3
}
 
var es6 = {
  edition: 6,
  committee: "TC39",
  standard: "ECMA-262"
};

for (e in es6) {
  console.log(e); // edition, committee, standard
}								
							

for of

var planets = ["Mercury", "Venus", "Earth", "Mars"];

for (p of planets) {
  console.log(p); // Mercury, Venus, Earth, Mars
}
							

I can do it in simple for loop

Iterator

for (word of ["one", "two", "three"]) {
    alert(word);
}
 
var s = Set([1, 3, 4, 2, 3, 2, 17, 17, 1, 17]);
for (var v of s) {
    alert(v);
}
 
// Iterating over a Map produces key-value pairs: arrays of length 2.
var m = new Map;
m.set("one", 1);
m.set("two", 2);
for (var [name, value] of m) {
    alert(name + " = " + value);
}
							
Harmony:Iterator

Utilities

String

  • startWith
  • endsWith
  • contains
  • toArray
String Extras

Number

  • isFinite
  • isInteger
  • isNaN
  • toInteger

Math

  • log10
  • log2
  • cosh
  • acosh
More Math Function

When?

  • November 2013: Final Draft
  • July 2014: editorially complete
  • December 2014: Ecma Approval

Support

ES6 Compatibility Table Traceur by Google es6-shim

Few Resources

2ality of Alex bRENDAN eICH Net tuts Sencha Addy Osmani New things to ES 6 Linq in ES6 Style Generator Another generator Browser fails

Thank you

http://bit.ly/1cVf9bJ

MD Khan / @mdkhan005