Trying Out JavaScript v.Next

Tuesday, April 10, 2012

ECMAScript Harmony is the future of JavaScript, and something you can experiment with using the stable builds of Chrome (my machine is currently running 18.0.1025.152 m, but that is subject to change at any minute).

The first step is going into chrome://flags, and flipping the "Enable Experimental JavaScript" bit.

Enabling Experimental JavaScript in Chrome

I'm looking forward to let and proxies.

Let

You might know that the JavaScript we use today has only function scope and global scope. There is no block scope, and the following test will pass without any difficulty (x is scoped to the doWork function, not the block inside the conditional).

test("there is no block scope", function () {
    "use strict";    

    var doWork = function() {
        
        if(true)
        {
            var x = 3;
        }
        return x;
    };

    var result = doWork();
    strictEqual(result, 3);
});

 

Change the code to use the new let keyword, and the behavior is dramatically different (the return statement in doWork will throw an exception).

test("let has block scope", function () {
    "use strict";

    var error;
    var doWork = function() {
        
        if(true)
        {
            let x = 3;
        }
        return x;
    };

    try {
        var result = doWork();    
    }
    catch(ex) {
        error = ex;
    }

    strictEqual(error.name, "ReferenceError");

});

Proxies

Proxies will give JavaScript method_missing and interception / call trap capabilities. I can imagine the data-binding and MVVM frameworks being much less intrusive if they fully embrace proxies.  In fact, I can see proxies solving all sorts of problems from data-binding to DOM inconsistencies.

test("Use a proxy", function() {

    var p = Proxy.create({
                get: function(proxy, name) {
                    return "You read " + name;
                }
            });

    var result = p.fooBar;

    strictEqual(result, "You read fooBar");
});
Now we just need to wait until this code isn't considered "experimental"...

Comments
gravatar Rob Eisenberg Tuesday, April 10, 2012
Honestly, Harmony can't get here fast enough. It's going to significantly advance the state of JavaScript.
gravatar Theo Vosse Wednesday, April 11, 2012
What's that last thing doing in the language? Is it meant for job safety? Because that's a grand way to make unreadable code...
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!