26 Dec 2011

ECMAScript harmony features in Chrome Canary

The latest Canary build of Google Chrome allows you to unlock some new features from ECMAScript Harmony. However, they are disabled by default, so to enable them you have to type about:flags into your address bar, and turn on “Enable Experimental JavaScript” which is found right at the bottom of the page.

Now, you have access to proxies, weak maps, maps, and sets!

Proxies

I am very excited about the Proxy API – it will allow you to create objects whose properties can be computed at run-time dynamically, and for hooking into other objects for auditing and logging purposes. A simple example:

var proxyObj = Proxy.create({
  get: function(obj, propertyName) {
    return 'Hello, '+ propertyName;
  }
});
 
console.log(proxyObj.John); // "Hello, John"

You can do all kinds of meta programming stuff using Proxies (that’s probably another blog post).

Maps and Weak Maps

The use of Maps and WeakMaps allows you to create dicts where the keys are objects.

var m = new Map();
var obj = {foo: "bar"};
m.set(obj, "baz");
m.get(obj);   // "baz"

The difference between a WeakMap and Map is that the WeakMap is not enumerable. Although the Map is enumerable, it relies on the iterator proposal, which is yet to be implemented in V8. So for all practical purposes, the Map and WeakMap are essentially the same for now.

Set

Again, you can add, delete and check for existence of a value in a Set, but cannot yet iterate through it.

var s = new Set();
s.add(2);
s.has(2); // true
s.had(10); // false

Finally, there was is a small but significant change in the way typeof operates on null. In ES3:

typeof null === 'object';  // true

But in ES5:

typeof null === 'null';  // true

This page from ECMAScript Harmony Wiki talks more about this semantic change, and how to support both ES5 and ES3 when writing code.

The immediate value of any of these features to browser-side JavaScript development is probably none, but nevertheless I’m excited to see the roll out of ES5 and ES6 features into V8, so we can start using them soon on atleast node.js.

You can follow me on Twitter right here.

Tagged with:

Leave a Reply