JavaScript Next – ES6 Harmony – Default Parameters



JavaScript Next – ES6 Harmony – Default Parameters

0 0


jschannel-es6

Slides for talk at JSChannel NCR

On Github sankha93 / jschannel-es6

JavaScript Next

ES6 Harmony

Sankha Narayan Guria / @sankha93

This is me

I am sankha93 on Twitter, Github, IRC.

JavaScript?

Language is evolving. Fast!Iterations, Inline Functions, Blah blah...

ECMAScript 6

Get ready for the future. Now.

Default Parameters

Define your parameter defaults in the function signature itself.

No more doing this:

if (!myMissingParameter)
    myMissingParameter = 0;

Default Parameters

Just write your code like this instead:

function myFunc(a, b = 1, c = 0) {
    // ... function body is here
}

Default Parameters

Or some expressions as well.

function myFunc(a = 0, b = a*a, c = b*a) {
    return [a, b, c];
}

// myFunc(5); evaluates to [5, 25, 125]

Rest Parameters

Handle indefinite number of parameters?

function myFunc(a, b, ...r) {
    console.log(Array.isArray(r));
    return r.concat([a, b]);
}

Rest Parameters

> myFunc(1, 2);
true
[1, 2]

Rest Parameters

> myFunc(1, 2, 3, 4, 5);
true
[3, 4, 5, 1, 2]

Spread

The dual of the rest parameters.

> var a = [3, 4, 5];
> [1, 2, ...a];
[1, 2, 3, 4, 5]

Spread

You can even use it in expressions as well!

function f(...r) {
    return r;
}

function g(a) {
    return f(...a);
}
We just broke up an array into a individial parameter list.

Sets

The name says it. Its a set of arbitrary values.

> var s = new Set([1, true, "three"]);
> s.has(true);
true
> s.has("true");
false
> s.size();
3

Sets

Additional and deletion of elements is also easy.

> s.delete("three");
true
> s.has("three");
false
> s.add("two");
> s.size()
3

Maps

Key/Value pairs the JS way. Your keys aren't converted to strings implicitly.

var data = {val: "age"};
var m = new Map([[name, "sankha"], [data, 20]]);

> m.get(name);
"sankha"
> m.get(data);
20

WeakMap

Cycles between keys and values can tie up space in a Map. Weakmap comes to rescue!

> var objkey1 = {toString: function(){return "objkey1"}};
> var objkey2 = {toString: function(){return "objkey2"}};
> var wm = new WeakMap();
> wm.set(objkey1, objkey2);
> wm.set(objkey2, objkey1);
> wm.get(objkey1);
({toString:(function (){return "objkey2"})})

Iterators

for-of loops.

> for (var v of [1, 2, 3]) {
  console.log(v);
}
1
2
3

Iterators

Iterables from Sets and Maps.

> for (var e of set) {
  console.log(e);
}

> for (var [k, v] of map) {
  console.log(k, v);
}

Iterators

Iterate over keys, values and items.

> var s = new Set([1, 2, 3]);
> var it = set.keys();
> it = set.values();
> it = set.entries();
> it.next();
[1, 1]
> it.next();
[2, 2]
Applicable for any Iterables, Array, Sets, Maps.

Generators

Better way to create iterators. Each call to next() executes the function body till the next yield.

function myGenerator() {
  for (var i = 0; i < 3; i++)
    yield i * 2;
}

var g = myGenerator();
g.next(); // returns 0
g.next(); // returns 2
g.next(); // returns 4
g.next(); // throws StopIteration

Proxy

To enable ES programmers to represent virtualized objects (proxies).

> var MethodSink = Proxy({}, {
  has: function(target, name) { return true; },
  get: function(target, name, receiver) {
    if (name in Object.prototype) {
      return Object.prototype[name];
    }
    return function(...args) {
      return receiver.__noSuchMethod__(name, args);
    }
  }
});

Proxy

Lets create a default __noSuchMethod__.

> Object.defineProperty(
  Object.prototype,
  '__noSuchMethod__',
  {
    configurable: true,
    writable: true,
    value: function(name, args) {
      throw new TypeError(name + " is not a function");
    }
  }
);

Proxy

Lets add MethodSink to the end of the prototype chain.

> var obj = {
      foo: 1 ,
      __proto__: MethodSink,
      __noSuchMethod__: function(name, args) {
        return name;
      }
    }
> obj.foo
1
> obj.bar()
"bar"
> obj.toString
function toString() {
    [native code]
}

Proxy

We can now proxy __noSuchMethod__.

> obj.bar
(function (...args) {
      return receiver.__noSuchMethod__(name, args);
    })
> var foo = obj.bar
js> foo()
"bar"

Arrow Functions

Shorter function expressions.

> var square = x => x * x;
> square(5)
25

Arrow Functions

Take a look at this peice of code.

function Person(){
  this.age = 0;

  setInterval(function growUp(){
    this.age++;
  }, 1000);
}

var p = new Person();

Arrow Functions

Arrow functions lexically bind the this value.

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++;
  }, 1000);
}

var p = new Person();

Modules

They are eh, modules?

module FastMath {
    export function sin() { /*...*/ }
    export function cos() { /*...*/ }
}

import {sin, cos} from FastMath;

In-built methods

  • String startsWith, endsWith, contains, repeat
  • Number isNaN, isFinite, toInteger, isInteger
  • Number of Math functions

Lots More

There are many more things being planned.Classes, Modules, etc.

Read the spec

The spec is publicly available online at ECMAScript Wiki.

Experiment

Partially implemented in SpiderMonkey and V8. Try on Firefox Nightly and Google Chrome and report bugs.

Note: Turn on Experimental JavaScript in Google Chrome via chrome://flags

Thank you!

Questions?