<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
	    xml:lang="en-US" 
	    xml:base="http://peter.michaux.ca">
  <id>http://peter.michaux.ca/</id>
  <title>peter.michaux.ca</title>
  <updated>2013-06-02T19:05:00-07:00</updated>
  <link href="/feed/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="/" rel="alternate" type="text/html"/>

<entry>
    <id>http://peter.michaux.ca/articles/introducing-maria-the-real-mvc</id>
    <title>Introducing Maria: The Real MVC</title>
    <updated>2013-06-02T19:05:00Z</updated>
    <link href="/articles/introducing-maria-the-real-mvc" rel="alternate" type="text/html"/>
		<content type="html">&lt;p&gt;In December 2011, &lt;a href=&quot;http://www.jamesladdcode.com/&quot; target=&quot;_blank&quot;&gt;James Ladd&lt;/a&gt; and I were chatting about JavaScript, its dynamic nature, and program design. During the discussion, James asked detailed questions and I needed to illustrate a few points about MVC. I created &lt;a href=&quot;https://github.com/petermichaux/maria&quot;&gt;a GitHub repository&lt;/a&gt; with code we could discuss.&lt;/p&gt;

&lt;p&gt;Fast forward 1.5 years, though many more conversations, much more research, testing, and refining, and &lt;a href=&quot;http://peter.michaux.ca/maria/&quot;&gt;the Maria framework&lt;/a&gt; for building MVC application in JavaScript is 1.0.0!&lt;/p&gt;

&lt;p&gt;Over the past several years, the JavaScript community has been inundated with MV* frameworks. In the wake of the one-page app explosion, many JavaScript developers searched for ways to structure their larger browser applications more manageably. You can see in the source code of the frameworks that the authors were struggling away on their own attempting to solve the same problems. I&amp;rsquo;m willing to bet they went through a similar process I did trying to find discussions tailored to JavaScript about this famous MVC that was supposed to solve all their problems and more.&lt;/p&gt;

&lt;p&gt;Why no one else chose to write an true MVC framework, I cannot figure. There is no doubt that the early Smalltalk MVC architecture inspired today&amp;rsquo;s MV* frameworks for JavaScript. My take on it was straight forward. The MVC architecture has withstood a 30 year test. It has passed that brutal test. It is still used for application programming. It is very useful for browser programming. Why not take this time-tested architecture and make a JavaScript framework true to the MVC that is implemented in &lt;a href=&quot;http://www.squeak.org&quot; target=&quot;_blank&quot;&gt;Squeak Smalltalk&lt;/a&gt; and written about in &lt;a href=&quot;http://www.amazon.com/gp/product/0201633612/ref=as_li_tf_tl?ie=UTF8&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=0201633612&amp;amp;linkCode=as2&amp;amp;tag=petermichauxc-20&quot;&gt;Design Patterns&lt;/a&gt;&lt;img src=&quot;http://www.assoc-amazon.com/e/ir?t=petermichauxc-20&amp;amp;l=as2&amp;amp;o=1&amp;amp;a=0201633612&quot; width=&quot;1&quot; height=&quot;1&quot; border=&quot;0&quot; alt=&quot;&quot; style=&quot;border:none !important; margin:0px !important;&quot;&gt;? My experience with Maria has shown it was a good choice.&lt;/p&gt;

&lt;p&gt;How true is Maria to the real MVC? Somewhere along the way, I downloaded the Smalltalk Squeak implementation, found the model, view, and controller classes, and started porting lines of Smalltalk to JavaScript. In places, the two really are that close. And it wasn&amp;rsquo;t like pounding a square peg in a round hole. It was a natural fit. As my detailed understanding of the Smalltalk implementation improved, more of my &amp;ldquo;creative&amp;rdquo; lines of code in the growing Maria were deleted and in their place appeared more ported lines from Smalltalk. Every single time it was an improvement. The Squeak classes have been around a long time. They are some of the best lines of code in all the world&amp;rsquo;s aggregate of software. They are a solid foundation on top of which to build an important application.&lt;/p&gt;

&lt;p&gt;So if you want to build your applications on a solid foundation, I recommend you check out &lt;a href=&quot;http://peter.michaux.ca/maria/&quot;&gt;the Maria framework&lt;/a&gt;.&lt;/p&gt;
</content>
</entry>

<entry>
    <id>http://peter.michaux.ca/articles/early-mixins-late-mixins</id>
    <title>Early Mixins, Late Mixins</title>
    <updated>2012-10-26T23:17:00Z</updated>
    <link href="/articles/early-mixins-late-mixins" rel="alternate" type="text/html"/>
		<content type="html">&lt;p&gt;In JavaScript, the language supplies us with several code reuse patterns. Prototype chaining gives us the primary single inheritance mechanism. Mixins are also an important pattern when we want one object to &amp;ldquo;inherit&amp;rdquo; functionality from multiple objects. There are several ways to implement the mixin process. This article looks at two contrasting implementations: early mixins and late mixins.&lt;/p&gt;

&lt;h2&gt;Late Binding&lt;/h2&gt;

&lt;p&gt;Let&amp;rsquo;s start with a quick review of what late binding gives us.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var adam = {
    greet: function() {
        return &quot;hello&quot;;
    }
};

adam.greet(); // &quot;hello&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we ask &lt;code&gt;adam&lt;/code&gt; to &lt;code&gt;greet&lt;/code&gt;, the method to be executed is looked up at the time of the call. This is late binding and means if we redefine the greet method, subsequent calls will use the new definition.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;adam.greet = function(name) {
    return &quot;hello&quot; + (name ? (&quot;, &quot; + name) : &quot;&quot;);
};

adam.greet(&quot;world&quot;); // &quot;hello, world&quot;;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This ability to redefine a method is valuable because it makes it possible for plugins to modify the behaviour of an existing code library.&lt;/p&gt;


&lt;h2&gt;Late Binding and Prototype Chaining&lt;/h2&gt;

&lt;p&gt;How does late binding work with prototype chaining? Let&amp;rsquo;s start with a fresh example. First we&amp;rsquo;ll make a new object &lt;code&gt;adam&lt;/code&gt; who introduces himself.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var adam = {
    _name: &quot;Adam&quot;;
    greet: function() {
        return &quot;hello. I am &quot; + this._name;
    }
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Someone named Adam seems like a suitable prototype for all existing people. We can make a constructor function to produce more people.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Person(name) {
    this._name = name;
}
Person.prototype = adam;

var eve = new Person(&quot;Eve&quot;);
eve.greet(); // &quot;hello. I am Eve&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Thanks to the combination of late binding and the prototype chain, a change to &lt;code&gt;adam&lt;/code&gt; will result in a change to &lt;code&gt;eve&lt;/code&gt; instantly. The following could be some plugin for the library that provides the &lt;code&gt;adam&lt;/code&gt; object. This redefinition could happen at runtime due to user interaction.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;adam.greet = function(name) {
    return &quot;hello&quot; + (name ? (&quot;, &quot; + name) : '') + &quot;. I am &quot; + this._name;
};

eve.greet(&quot;world&quot;); // &quot;hello, world. I am Eve&quot;&lt;/code&gt;&lt;/pre&gt;


&lt;h2&gt;Early Mixins&lt;/h2&gt;

&lt;p&gt;Another way to create a reusable bunch of code as a library is to provide one object who&amp;rsquo;s properties can be mixed into another object. This is usually done with an early mixin implementation.&lt;/p&gt;

&lt;p&gt;First, a generic function that can mix properties from one object into another object.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function earlyMixin(sink, source) {
    for (var property in source) {
        sink[property] = source[property];
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now a object containing methods that would be useful on another object. Here is a library called Speeches.JS.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var speeches = {
    greet: function() {
        return &quot;hello. I am &quot; + this._name;
    },
    farewell: function() {
        return &quot;goodbye. I am &quot; + this._name;
    }
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since this Speeches.JS library is already written and well unit tested, we&amp;rsquo;d like to reuse that code in our code.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Person(name) {
    this._name = name;
}
earlyMixin(Person.prototype, speeches);

var adam = new Person('Adam');
adam.greet(); // &quot;hello. I am Adam&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now suppose we have mixed this &lt;code&gt;speeches&lt;/code&gt; object into several other objects (like the &lt;code&gt;Person.prototype&lt;/code&gt; object.) Also suppose we want to modify the &lt;code&gt;speeches&lt;/code&gt; object at some later time and have all objects who&amp;rsquo;ve had the &lt;code&gt;speeches&lt;/code&gt; object mixed into it be updated. This is what a plugin for Speeches.JS might want to do.&lt;/p&gt; 

&lt;pre&gt;&lt;code&gt;speeches.greet = function(name) {
    return &quot;hello&quot; + (name ? (&quot;, &quot; + name) : '') + &quot;. I am &quot; + this._name;
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Unfortunately we cannot do this because the &lt;code&gt;speeches&lt;/code&gt; methods have been mixed into the &lt;code&gt;Person.prototype&lt;/code&gt; object early (i.e. at the time of mixin.) We still have&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;adam.greet(&quot;world&quot;); // &quot;hello. I am Adam&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Late Mixins&lt;/h2&gt;

&lt;p&gt;In order to make it possible to modify &lt;code&gt;speeches&lt;/code&gt; and have all objects use the modified methods, we need one level of indirection in the mixin process.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function lateMixin(sink, source) {
    for (var property in source) {
        (function(property) {
            sink[property] = function() {
                return source[property].apply(this, arguments);
            }
        }(property));
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Instead of directly borrowing the methods of the &lt;code&gt;source&lt;/code&gt;, the &lt;code&gt;sink&lt;/code&gt; is given methods that call the methods of &lt;code&gt;source&lt;/code&gt;. This means that the method on &lt;code&gt;source&lt;/code&gt; are mixed in late because they are looked up when they are called (rather than when they are mixed in.)&lt;/p&gt;

&lt;p&gt;Now we can go through the same example with a different result.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var speeches = {
    greet: function() {
        return &quot;hello. I am &quot; + this._name;
    },
    farewell: function() {
        return &quot;goodbye. I am &quot; + this._name;
    }
};

function Person(name) {
    this._name = name;
}
lateMixin(Person.prototype, speeches);

var adam = new Person('Adam');
adam.greet(); // &quot;hello. I am Adam&quot;

speeches.greet = function(name) {
    return &quot;hello&quot; + (name ? (&quot;, &quot; + name) : '') + &quot;. I am &quot; + this._name;
};

adam.greet(&quot;world&quot;); // &quot;hello, world. I am Adam&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When &lt;code&gt;adam.greet&lt;/code&gt; is called it uses the most recent definition of &lt;code&gt;speeches.greet&lt;/code&gt;. Yay! Late mixins have given us the same dynamic power that late binding and the prototype chain give us. This makes a library like Speeches.JS more flexible and opens it up for various kinds of modification at run time.&lt;/p&gt;

&lt;h2&gt;Not Quite Everything&lt;/h2&gt;

&lt;p&gt;Late mixins give us some of the power of late binding and the prototype chain but not everything. If we add another method to the &lt;code&gt;speeches&lt;/code&gt; object it is not added to the other objects into which &lt;code&gt;speeches&lt;/code&gt; has been mixed. There are several ways to accomplish this type of functionality. Something like &lt;a href=&quot;http://wiki.ecmascript.org/doku.php?id=harmony%3adirect_proxies&quot; target=&quot;_blank&quot;&gt;proxies&lt;/a&gt; might be our answer to get closer to real multiple inheritance.&lt;/p&gt;
</content>
</entry>

<entry>
    <id>http://peter.michaux.ca/articles/uMVC</id>
    <title>uMVC - A micro MVC framework in JavaScript</title>
    <updated>2012-10-13T20:00:00Z</updated>
    <link href="/articles/uMVC" rel="alternate" type="text/html"/>
		<content type="html">&lt;p&gt;&lt;a href=&quot;https://twitter.com/petermichaux/status/221671174915104768&quot; title=&quot;@petermichaux on Twitter&quot; target=&quot;_blank&quot;&gt;I tweeted:&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You can write an MVC framework in one hundred lines of JavaScript &amp;amp; write about its effective use for one hundred thousand lines of English.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I wondered exactly how small I could write a respectable MVC framework that included the three fundamental design patterns of the traditional Smalltalk-style MVC: the observer, composite, and strategy patterns.&lt;/p&gt;

&lt;p&gt;See &lt;a href=&quot;https://github.com/petermichaux/uMVC/blob/master/uMVC.js&quot; target=&quot;_blank&quot;&gt;the uMVC code on Github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Hopefully this code is educational for those new to the MVC paradigm. I think this code is something every JavaScript programmer should understand inside out and be able to explain every individual line&amp;rsquo;s significance to another programmer new to MVC.&lt;/p&gt;

&lt;p&gt;If you are looking for a more fully-featured MVC framework that follows the same principles of uMVC to use in real browser applications, I suggest you take a look at &lt;a href=&quot;https://github.com/petermichaux/maria&quot; target=&quot;_blank&quot;&gt;Maria&lt;/a&gt;.&lt;/p&gt;
</content>
</entry>

<entry>
    <id>http://peter.michaux.ca/articles/less-English-more-JavaScript</id>
    <title>Less English, more JavaScript</title>
    <updated>2012-10-13T19:00:00Z</updated>
    <link href="/articles/less-English-more-JavaScript" rel="alternate" type="text/html"/>
		<content type="html">&lt;p&gt;I haven&amp;rsquo;t written much for my website this year. It wasn&amp;rsquo;t an accident. I wasn&amp;rsquo;t too busy. It was a choice. My new year&amp;rsquo;s resolution for 2012 was to write less English and more JavaScript.&lt;/p&gt;

&lt;p&gt;Three quarters of the year is now gone and I feel like I&amp;rsquo;ve satisfied that resolution with 11 new JavaScript repositories &lt;a href=&quot;https://github.com/petermichaux&quot; target=&quot;_blank&quot;&gt;on Github&lt;/a&gt;. Most of the work was driven by the development of the &lt;a href=&quot;https://github.com/petermichaux/maria&quot; target=&quot;_blank&quot;&gt;Maria framework&lt;/a&gt; for writing MVC-style browser application. That particular project has been great fun and satisfying.&lt;/p&gt;

&lt;p&gt;Now I feel as through I should tell the world about these projects &amp;hellip; but part of me just wants to continue writing more JavaScript.&lt;/p&gt;

</content>
</entry>

<entry>
    <id>http://peter.michaux.ca/articles/organizing-browser-application-files</id>
    <title>Organizing Browser Application Files</title>
    <updated>2012-10-12T23:00:00Z</updated>
    <link href="/articles/organizing-browser-application-files" rel="alternate" type="text/html"/>
		<content type="html">&lt;p&gt;If you are building a large, one-page browser application with the usual suspects of HTML, CSS, JavaScript, images, etc, you&amp;rsquo;ll have many files and staying organized is important. Here is a way to organize your files.&lt;/p&gt;


&lt;h2&gt;General Structure&lt;/h2&gt;

&lt;pre&gt;&lt;code&gt;MyApp/
    Makefile
    README
    etc/
    lib/
    src/
    tst/&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Perhaps the first thing you will do when starting the project is fill the &lt;code&gt;lib&lt;/code&gt; directory with all the third-party libraries you know you&amp;rsquo;ll be using. These libraries are dropped into the &lt;code&gt;lib&lt;/code&gt; directory without modification. Just plop them there in the same form they are distributed. You aren&amp;rsquo;t allowed to edit these files. This directory is the only directory where you put files created by a third party.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;src&lt;/code&gt; directory contains all of the files that you create and write that will become part of the files downloaded by the browser of a user of your application. These are the files we are excited about writing.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;tst&lt;/code&gt; directory contains all the files that test the files in the &lt;code&gt;src&lt;/code&gt; directory. These are the files we are not excited about writing.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Makefile&lt;/code&gt; has a default &lt;code&gt;build&lt;/code&gt; target that generates the directory called &lt;code&gt;bld&lt;/code&gt; which is filled with production-ready files that can be copied to the production web servers. The files in the &lt;code&gt;lib&lt;/code&gt; and &lt;code&gt;src&lt;/code&gt; directories are combined, minified, compressed, and otherwise mutated to become the files in the &lt;code&gt;bld&lt;/code&gt; directory. This target can possibly generate a &lt;code&gt;MyApp.tar.gz&lt;/code&gt; file if that is how the distribution to production will be done.&lt;/p&gt;

&lt;p&gt;The build process may be guided by data in files in the &lt;code&gt;etc&lt;/code&gt; directory. For example, there may be manifest files that state which files are concatenated together during the build and the name of the resulting files. Exactly which files with which data are in your &lt;code&gt;etc&lt;/code&gt; directory depend on which tools you are using in your build process.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Makefile&lt;/code&gt; should have a &lt;code&gt;clean&lt;/code&gt; target that deletes the &lt;code&gt;bld&lt;/code&gt; directory.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Makefile&lt;/code&gt; might have a &lt;code&gt;test&lt;/code&gt; target that runs the tests in the &lt;code&gt;tst&lt;/code&gt; directory.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;README&lt;/code&gt; should at least explain what the targets in the Makefile do and how to run the tests.&lt;/p&gt;

&lt;p&gt;You should not need to run &lt;code&gt;make build&lt;/code&gt; in order to test your application either with the files in the &lt;code&gt;tst&lt;/code&gt; directory or in the browser while developing. You may have files in your &lt;code&gt;etc&lt;/code&gt; directory that control how the development environment is configured.&lt;/p&gt;


&lt;h2&gt;An MVC-style Application&lt;/h2&gt;

&lt;p&gt;You might be using an MVC framework like &lt;a href=&quot;https://github.com/petermichaux/maria&quot; target=&quot;_blank&quot;&gt;Maria&lt;/a&gt; to help structure your JavaScript. In this case, there is a natural way to divide your application at a finer scale.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;MyApp/
    Makefile
    README
    etc/
    lib/
        maria.js
    src/
        css/
        html/
            index.html
            templates/
        img/
        js/
            bootstrap.js
            controllers/
            models/
            views/
            util/
    tst/&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;index.html&lt;/code&gt; files is the page that the user loads into their browser to start the one-page application. This may be named something different like &lt;code&gt;myapp.html&lt;/code&gt;. This file loads the necessary CSS, image, template, and JavaScript files needed to run the application.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;templates&lt;/code&gt; directory contains any HTML templates used by your JavaScript views. These can be compiled to JavaScript and concatenated into one or a few JavaScript files during the build process.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;bootstrap.js&lt;/code&gt; file is the one with the call to &lt;code&gt;window.onload&lt;/code&gt; that fires up the whole application. It will start the loading of the data from the server, create the model layer, build the views, and add those views to the page so the user can begin interacting with the application.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;controllers&lt;/code&gt;, &lt;code&gt;models&lt;/code&gt;, and &lt;code&gt;views&lt;/code&gt; directories contain the obvious.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;util&lt;/code&gt; directory contains utility code that is not specific to any of the model, view, or controller layers. There may be pure functions that make computations with no side effects. You might have some obscure DOM related utilities that you wish were written by a third party for your &lt;code&gt;lib&lt;/code&gt; directory but that you have to write yourself for your unique browser scripting requirements.&lt;/p&gt;

</content>
</entry>

<entry>
    <id>http://peter.michaux.ca/articles/mixins-and-constructor-functions</id>
    <title>Mixins and Constructor Functions</title>
    <updated>2012-04-23T20:16:00Z</updated>
    <link href="/articles/mixins-and-constructor-functions" rel="alternate" type="text/html"/>
		<content type="html">&lt;p&gt;JavaScript allows programmers to take properties from one object and mix them into another object. There are several ways to accomplish this mixing and a few of them are explored here.&lt;/p&gt;


&lt;h2&gt;Observable Mixin&lt;/h2&gt;

&lt;p&gt;Here is a simple example of the observer pattern that can be mixed into other objects.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var observableMethods = {
    observe: function(observer) {
        if (!this.hasOwnProperty('observers')) {
            this.observers = [];
        }
        this.observers.push(observer);
    },
    notify: function(data) {
        if (this.hasOwnProperty('observers')) {
            for (var i=0, ilen=this.observers.length; i&amp;lt;ilen; i++) {
                this.observers[i](data);
            }
        }
    }
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It is possible to use the &lt;code&gt;observableMethods&lt;/code&gt; function as a observable itself.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;observableMethods.observe(function() {
    alert('hi');
});
observableMethods.notify();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A little mixin function to make other things observable.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function mixinObservable(sink) {
    for (var p in observableMethods) {
        if (observableMethods.hasOwnProperty(p) &amp;amp;&amp;amp;
            typeof observableMethods[p] === 'function') {
            sink[p] = observableMethods[p];
        }
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can mixin to an person created with an object literal.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var person = {
    name: 'Steve',
    setName: function(name) {
        var oldName = this.name;
        this.name = name;
        this.notify({oldName: oldName, newName: this.name});
    }
};
mixinObservable(person);
person.observe(function(data) {
    alert(data.oldName + ' was renamed to ' + data.newName);
});
person.setName('Sarah');&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Alternately we write a constructor function for observable people that we can rename.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Person(name) {
    this.setName(name);
};

mixinObservable(Person.prototype);

Person.prototype.setName = function(name) {
    var oldName = this.name;
    this.name = name;
    this.notify({oldName:oldName, newName:this.name});
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can then make a person and manipulate it.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var person = new Person('Steve');
person.observe(function(data) {
    alert(data.oldName + ' was renamed to ' + data.newName);
});
person.setName('Sarah');&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In all of the above code, the three uses of &lt;code&gt;hasOwnProperty&lt;/code&gt; are critical to understand.&lt;/p&gt;

&lt;p&gt;The first two uses of &lt;code&gt;hasOwnProperty&lt;/code&gt; in &lt;code&gt;observe&lt;/code&gt; and &lt;code&gt;notify&lt;/code&gt; ensure that the object into which the methods have been mixed, will have its own set observers and not share some set of observers with any other object. The unfortunate part is that these checks run every time the &lt;code&gt;observe&lt;/code&gt; and &lt;code&gt;notify&lt;/code&gt; methods are called. This is inefficient and something we want to fix.&lt;/p&gt;

&lt;p&gt;The third use of &lt;code&gt;hasOwnProperty&lt;/code&gt; in &lt;code&gt;mixinObservable&lt;/code&gt; means that only properties directly on &lt;code&gt;observableMethods&lt;/code&gt; will be mixed into other objects. This is important because if we do not use &lt;code&gt;hasOwnProperty&lt;/code&gt; then we copy all of the enumerable &lt;code&gt;Object.prototype&lt;/code&gt; properties which is either wasteful or will overwrite any custom methods with the same names on other objects.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;mixinObservable&lt;/code&gt; function also copies only functions. If this check was not made and someone had observed the &lt;code&gt;observableMethods&lt;/code&gt; object itself then the &lt;code&gt;observableMethods.observes&lt;/code&gt; array would be copied as part of every mixin and observers would be shared by some observable objects (e.g. &lt;code&gt;observableMethods&lt;/code&gt; and &lt;code&gt;Person.prototype&lt;/code&gt; in the example above.)&lt;/p&gt;

&lt;p&gt;A simpler &lt;code&gt;mixinObservable&lt;/code&gt; method could be the following but this could be more difficult to maintain. If more methods are added to &lt;code&gt;observableMethods&lt;/code&gt; then they need to be explicitly listed in &lt;code&gt;mixinObservable&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function mixinObservable(sink) {
    sink.observe = observableMethods.observe;
    sink.notify = observableMethods.notify;
}&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Fixing the Inefficiency&lt;/h2&gt;

&lt;p&gt;The inefficiency in &lt;code&gt;observe&lt;/code&gt; and &lt;code&gt;notify&lt;/code&gt; can be fixed by making a constructor function for &lt;code&gt;Observable&lt;/code&gt; objects.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Observable() {
    this.observers = [];
}
Observable.prototype.observe = function(observer) {
    this.observers.push(observer);
};
Observable.prototype.notify = function(data) {
    for (var i=0, ilen=this.observers.length; i&amp;lt;ilen; i++) {
        this.observers[i](data);
    }
};
Observable.call(Observable.prototype); // optional depending what you want&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the &lt;code&gt;observe&lt;/code&gt; and &lt;code&gt;notify&lt;/code&gt; methods of an observable function are more efficient as we know the &lt;code&gt;observers&lt;/code&gt; property was created when the &lt;code&gt;Observable&lt;/code&gt; constructor function ran.&lt;/p&gt;

&lt;p&gt;The last line, &lt;code&gt;Observable.call(Observable.prototype);&lt;/code&gt;, is a bit of an unusual one but it makes it possible to observe &lt;code&gt;Observable.prototype&lt;/code&gt; just like &lt;code&gt;observableMethods&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A new mixin function.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function mixinObservable(sink) {
    for (var p in Observable.prototype) {
        if (Observable.prototype.hasOwnProperty(p) &amp;amp;&amp;amp;
            typeof Observable.prototype[p] === 'function') {
            sink[p] = Observable.prototype[p];
        }
    }
    Observable.call(sink); // optional depending what you want
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Mixing into a person created with an object literal just like it was done above. The last line of this new &lt;code&gt;mixinObservable&lt;/code&gt; insures the &lt;code&gt;observers&lt;/code&gt; property is created.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var person = {
    name: 'Steve',
    setName: function(name) {
        var oldName = this.name;
        this.name = name;
        this.notify({oldName: oldName, newName: this.name});
    }
};
mixinObservable(person);
person.observe(function(data) {
    alert(data.oldName + ' was renamed to ' + data.newName);
});
person.setName('Sarah');&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The trick comes when we create a &lt;code&gt;Person&lt;/code&gt; constructor function.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Person(name) {
    Observable.call(this);
    this.setName(name);
};

mixinObservable(Person.prototype);

Person.prototype.setName = function(name) {
    var oldName = this.name;
    this.name = name;
    this.notify({oldName:oldName, newName:this.name});
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first line of the constructor function, &lt;code&gt;Observable.call(this);&lt;/code&gt;, ensures that each &lt;code&gt;Person&lt;/code&gt; object has its own set of observers. Without this call, all the people will share the same list of observers which is the set of observers on the &lt;code&gt;Person.prototype&lt;/code&gt; object. If this makes you squint then it is well worth the effort to think about it until it is clear why.&lt;/p&gt;

&lt;p&gt;To use some class vocabulary, the first line of the constructor function can be thought of as a &lt;code&gt;super&lt;/code&gt; call and that the Person class inherits from the Observable class. Some JavaScript diehards cringe at the mention of this vocabulary but I think the comparison is worth consideration.&lt;/p&gt;


&lt;h2&gt;Multiple Mixins&lt;/h2&gt;

&lt;p&gt;Multiple mixins follow the same pattern.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Person(name) {
    Observable.call(this);
    Common.call(this);
    this.setName(name);
}

mixinObservable(Person.prototype);
mixinCommon(Person.prototype);

// By coincidence mixinCommon also added a notify method which
// clobbered the method of the same name added by mixinObservable.
// Fix this problem making appropriate decisions about how
// to call both.
Person.prototype.notify = function() {
    Common.prototype.notify.call(this);
    Observable.prototype.notify.apply(this, arguments);
};
// ...&lt;/code&gt;&lt;/pre&gt;


&lt;h2&gt;Prototype Chaining vs. Mixins&lt;/h2&gt;

&lt;p&gt;There is one primary difference between prototype chaining and mixins. For example,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Person(name) {
    Observable.call(this);
    Base.call(this);
    this.setName(name);
}

// chain prototypes so that all Person objects
// inherit from Base.prototype.
Person.prototype = Object.create(Base.prototype);
Person.prototype.constructor = Person;
Base.call(Person.prototype); // optional depending what you want

mixinObservable(Person.prototype);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now if we add methods to both &lt;code&gt;Base.prototype&lt;/code&gt; and &lt;code&gt;Observable.prototype&lt;/code&gt; &lt;em&gt;after&lt;/em&gt; the above code has executed. Only the method added to &lt;code&gt;Base.prototype&lt;/code&gt; will be added to &lt;code&gt;Person&lt;/code&gt; objects.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Base.prototype.getId = function() {/*...*/};
Observable.prototype.getObservers = function() {/*...*/};

var person = new Person('Steve');
person.getId(); // ok
person.getObservers(); // error: getObservers not defined&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Enjoy your mixins.&lt;/p&gt;

</content>
</entry>

<entry>
    <id>http://peter.michaux.ca/articles/our-backwards-dom-event-libraries</id>
    <title>Our Backwards DOM Event Libraries</title>
    <updated>2012-03-03T20:46:00Z</updated>
    <link href="/articles/our-backwards-dom-event-libraries" rel="alternate" type="text/html"/>
		<content type="html">&lt;h2&gt;The Browser APIs&lt;/h2&gt;

&lt;p&gt;A brief review of what the browsers give us to attach event listeners to DOM elements so we can do fancy stuff when the user interacts with the page.&lt;/p&gt;

&lt;p&gt;Internet Explorer gives us &lt;code&gt;element.attachEvent&lt;/code&gt; allowing us to attach a listener &lt;em&gt;function&lt;/em&gt; to an element.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;document.body.attachEvent(
    'onclick',
    function() {
        alert('body clicked');
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The other browsers give us &lt;code&gt;element.addEventListener&lt;/code&gt;. The use with which we are most familiar is supplying a listener &lt;em&gt;function&lt;/em&gt; as the second argument.&lt;p&gt;

&lt;pre&gt;&lt;code&gt;document.body.addEventListener(
    'click',
    function() {
        alert('body clicked');
    },
    false);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Many JavaScript programmers don&amp;rsquo;t know that it is also possible to send a listener &lt;em&gt;object&lt;/em&gt; as the second argument to &lt;code&gt;addEventListener&lt;/code&gt;. When an event is fired, the object&amp;rsquo;s &lt;code&gt;handleEvent&lt;/code&gt; method is called.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;document.body.addEventListener(
    'click',
    {
        handleEvent: function() {
            alert('body clicked');
        }
    },
    false);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;An important feature of using a listener &lt;em&gt;object&lt;/em&gt; is that the function value of it&amp;rsquo;s &lt;code&gt;handleEvent&lt;/code&gt; property is only looked up when the event is fired. This means that if the function value of the &lt;code&gt;handleEvent&lt;/code&gt; property changes between events then it is always the current value of the &lt;code&gt;handleEvent&lt;/code&gt; property that is called. This is late binding. For example,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var obj = {};

document.body.addEventListener('click', obj, false);

// click body will error in some browsers because
// no handleEvent method on obj

obj.handleEvent = function() {alert('alpha');};

// click body and see alert &quot;alpha&quot;

obj.handleEvent = function() {alert('beta');};

// click body and see alert &quot;beta&quot;

document.body.removeEventListener('click', obj, false);

// click body and see nothing
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Cross-Browser Libraries&lt;/h2&gt;

&lt;p&gt;Our cross-browser applications should not be cluttered with repetitive code to work with the different APIs provided by the different browsers, so we&amp;rsquo;ve abstracted the different APIs away in event libraries. This has been a very good choice.&lt;/p&gt;

&lt;p&gt;Different libraries have different APIs but every library has something like the following.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;LIB_addEventListener(
    document.body, 
    'click', 
    function() {
        alert('body clicked');
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;The JavaScript &lt;code&gt;this&lt;/code&gt; Wrinkle&lt;/h2&gt;
    
&lt;p&gt;A common problem with these library abstractions is when we want a method of an view object to be called when the event is fired. For example, in the following code, the value of &lt;code&gt;this&lt;/code&gt; in the &lt;code&gt;handleClick&lt;/code&gt; method is the global &lt;code&gt;window&lt;/code&gt; object. The alert will show &lt;code&gt;undefined&lt;/code&gt; when we may have expected to see the alert show &lt;code&gt;&quot;alpha&quot;&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function ViewObject() {
    this.data = 'alpha';
    LIB_addEventListener(
        document.body, 
        'click', 
        this.handleClick);
}
ViewObject.prototype.handleClick = function() {
    alert(this.data);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The workaround the libraries have given us (so that we can also still easily remove event listeners) is to specify the object we want as &lt;code&gt;this&lt;/code&gt; when the handler is called as an extra argument to the event library function. For example, the alert in this example will show &lt;code&gt;&quot;alpha&quot;&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function ViewObject() {
    this.data = 'alpha';
    LIB_addEventListener(
        document.body, 
        'click', 
        this.handleClick,
        this);
}
ViewObject.prototype.handleClick = function() {
    alert(this.data);
};
ViewObject.prototype.destroy = function() {
    LIB_removeEventListener(
        document.body,
        'click',
        this.handleClick,
        this
    );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One problem with this API is that the listener &lt;em&gt;function&lt;/em&gt; is bound when &lt;code&gt;LIB_addEventListener&lt;/code&gt; is called. This causes trouble when the function value of &lt;code&gt;handleClick&lt;/code&gt; is changed and then also when an attempt is made to remove the listener.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var vo = new ViewObject();

// click on the body and see alert &quot;alpha&quot;

vo.handleClick = function() {
    alert('beta');
};

// click on the body and still see &quot;alpha&quot;

vo.destroy();

// click on the body and still see &quot;alpha&quot;!
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Another problem is that we are writing the program in an object-oriented style but we are focusing on listener &lt;em&gt;functions&lt;/em&gt; rather than listener &lt;em&gt;objects&lt;/em&gt;. This mismatch is a clue to find a better solution.&lt;/p&gt;

&lt;h2&gt;A Library API for Listener Objects&lt;/h2&gt;

&lt;p&gt;Since we are frequently writing our programs in an object-oriented style, it makes sense to write &lt;code&gt;LIB_addEventListener&lt;/code&gt; so that it can accept listener &lt;em&gt;objects&lt;/em&gt; (as well as listener &lt;em&gt;functions&lt;/em&gt;.)&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var obj = {
    handleEvent: function() {
        alert('click handler');
    }
};
LIB_addEventListener(document.body, 'click', obj);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Frequently we have one view object handling multiple types of events for various elements. A fourth parameter specifying the method name would allow that easily and still keep late binding.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var obj = {
    handleMouseDown: function() {
        alert('mouse down handler');
    },
    handleMouseUp: function() {
        alert('mouse up handler');
    }
};
LIB_addEventListener(document.body, 'mousedown', obj, 'handleMouseDown');
LIB_addEventListener(document.body, 'mouseup', obj, 'handleMouseUp');
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This API still allows for listener &lt;em&gt;functions&lt;/em&gt; by looking at the type of the third argument.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;LIB_addEventListener(document.body, 'mousedown', function() {
    alert('mousedown');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But now there is no need for specifying the &lt;code&gt;this&lt;/code&gt; object that will be used when the listener &lt;em&gt;function&lt;/em&gt; is called because we have something better suited to the task: listener &lt;em&gt;objects&lt;/em&gt;.&lt;/p&gt;

</content>
</entry>

<entry>
    <id>http://peter.michaux.ca/articles/scheme-from-scratch-royal-scheme-v0_1-integers</id>
    <title>Scheme from Scratch - Royal Scheme v0.1 - Integers</title>
    <updated>2011-07-29T17:50:00Z</updated>
    <link href="/articles/scheme-from-scratch-royal-scheme-v0_1-integers" rel="alternate" type="text/html"/>
		<content type="html">&lt;p&gt;It took a while but the plan is back on track. Royal Scheme is a go.&lt;/p&gt;

&lt;p&gt;I&amp;rsquo;ve been picking away at the project at a leisurely pace trying to determine exactly what it will be. Blog articles seem like a great way to keep folks informed about the state of development. Hopefully some folks will want to follow along creating their own implementations again like they did with Bootstrap Scheme. It was a whole bunch of fun.&lt;/p&gt;

&lt;p&gt;I think a book format would be a better format for truly documenting the iterative development of a real Scheme interpreter that is implemented in C. I still haven&amp;rsquo;t found that book and if I was taking a university course then I&amp;rsquo;d want to take the course that has that book as its primary text. So a lot of what Royal Scheme development will be about is ensuring the order of introducing features is just right and that the concepts underlying the implementation are explained in code comments and in a book. It is a lofty goal. We&amp;rsquo;ll see how it goes. I&amp;rsquo;m hoping for feedback from you.&lt;/p&gt;

&lt;p&gt;Just as Bootstrap Scheme started with integers, so does Royal Scheme.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ ./scm
Welcome to Royal Scheme. Ctrl-c to exit.
&gt; 123
123
&gt; -123
-123
&gt; +007
7
&gt; ^C
$&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I&amp;rsquo;ve put the code on github. I&amp;rsquo;m new to git and github which adds a bit more flavor to the project. You can browse the code at the following address&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://github.com/petermichaux/royal-scheme&quot;&gt;http://github.com/petermichaux/royal-scheme&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and I created a branch specifically for this integers-only version&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/petermichaux/royal-scheme/tree/v0.1&quot;&gt;https://github.com/petermichaux/royal-scheme/tree/v0.1&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can get the code with the following command&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ git clone https://github.com/petermichaux/royal-scheme.git&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;You should be able to just run &lt;code&gt;make&lt;/code&gt; and then the above REPL session example should work.&lt;/p&gt;

&lt;p&gt;I&amp;rsquo;m hoping you will scrutinize the code and really give me grief that I&amp;rsquo;ve done something silly, stupid, overly complex, have a trailing space on a line, haven&amp;rsquo;t written a comment where a comment would be helpful, etc. I&amp;rsquo;m particularly interested in what you think of checking the return value of &lt;code&gt;printf&lt;/code&gt; and &lt;code&gt;scm_write&lt;/code&gt; in &lt;code&gt;repl&lt;/code&gt;. It doesn&amp;rsquo;t feel right quite to me. Also the overflow checking in &lt;code&gt;scm_read_number&lt;/code&gt; happens each iteration which is not as efficient as it possibly could be.&lt;/p&gt;

&lt;p&gt;By the way, registration for the &lt;a href=&quot;http://scheme2011.ucombinator.org/&quot;&gt;Scheme 2011 Workshop&lt;/a&gt; will open in August. I&amp;rsquo;m planning on going and hoping to talk with some people there about Royal Scheme.&lt;/p&gt;

&lt;p&gt;
  Previous article: &lt;a href=&quot;/articles/scheme-from-scratch-royal-scheme-planning&quot;&gt;Introduction&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

</content>
</entry>

<entry>
    <id>http://peter.michaux.ca/articles/javascript-is-dead-long-live-javascript</id>
    <title>JavaScript is Dead. Long Live JavaScript!</title>
    <updated>2011-06-25T20:21:00Z</updated>
    <link href="/articles/javascript-is-dead-long-live-javascript" rel="alternate" type="text/html"/>
		<content type="html">&lt;p&gt;For 16 years, JavaScript has been the language of the web browser. This language has enabled the building of compelling web applications and contributed to the success of the web. Other scripting languages could have filled the role JavaScript does but JavaScript was in the right place at the right time. Microsoft added Basic to Internet Explorer a long time ago but JavaScript was the language in all the browsers and so it won. Since JavaScript has been cross-browser and at least good enough, the browser makers have not needed to add other language interpreters to the browsers themselves.&lt;/p&gt;

&lt;p&gt;But we still didn&amp;rsquo;t choose to use JavaScript. It has been the one option. It has powerful features like closures and we learned to love these features while turning a blind eye to the warty parts of the language. There has even been a lot of apologizing to the programming community along the lines of &amp;ldquo;Yes we know it is a pretty funky language but please give it a chance. I&amp;rsquo;m sure you&amp;rsquo;ll learn to love it.&amp;rdquo; It shouldn&amp;rsquo;t be that hard to sell the quality of the language. JavaScript has been described as an experiment that escaped the lab a little too early and we&amp;rsquo;ve been stuck with the warts ever since.&lt;/p&gt;

&lt;p&gt;Still, JavaScript has been a great language. In 2007, Steve Yegge declared JavaScript as &lt;a href=&quot;http://steve-yegge.blogspot.com/2007/02/next-big-language.html&quot;&gt;The Next Big Language&lt;/a&gt; and it has been. Between then and now JavaScript-based web-applications have become bigger and better. With JavaScript&amp;rsquo;s help, the web has continued to flourish even with the threat of native mobile apps taking over the same space.&lt;/p&gt;

&lt;p&gt;In very recent times, JavaScript has been making its most successful attempt at being a server-side language. The Node.js platform, with its non-blocking I/O, may be solving a problem that programmers have needed solved for a long time. JavaScript is the language for Node.js and so JavaScript may go along for the ride to become a successful server-side language after many failed attempts in the past.&lt;/p&gt;

&lt;p&gt;Overall, JavaScript has been a wild success. The most popular programming language in the world. But if the browser died today, how much new JavaScript code would be written tomorrow? Most likely JavaScript would become a fringe language overnight. But the browser isn&amp;rsquo;t dying tomorrow. We will be programming for it for years to come.&lt;/p&gt;

&lt;p&gt;As JavaScript has been used for more and larger programs, the warts of the language have become more apparent and caused increasing amounts of grief for many developers. It may come as a surprise that even though I&amp;rsquo;ve written about JavaScript for years, I&amp;rsquo;m not a JavaScript fanboy. Most of my JavaScript articles have been about me working through the difficulties of finding a peaceful coexistence with the language. Yes I&amp;rsquo;ve enjoyed programming in JavaScript and have learned a lot but there certainly have been times when I&amp;rsquo;ve felt like I&amp;rsquo;m wallowing in the muck.&lt;/p&gt;

&lt;p&gt;One of the most obvious deficiencies in JavaScript is with its user interface: its syntax. The inability to quickly improve its syntax has lead to the language&amp;rsquo;s downfall.&lt;/p&gt;


&lt;h2&gt;The Case for Syntax Extensions: Verbose Idioms&lt;/h2&gt;

&lt;p&gt;Here we look at just four of the many examples where JavaScript&amp;rsquo;s syntax could be improved to remove verbose idioms from our daily programming existences.&lt;/p&gt;


&lt;h3&gt;Optional Parameters and Default Values&lt;/h3&gt;

&lt;p&gt;JavaScript functions can be called with a variable number of actual parameters. This makes some of the formal parameters in the function&amp;rsquo;s declaration optional. Often times these optional parameters must be set to a default value if no actual parameter is supplied. I&amp;rsquo;m willing to bet you&amp;rsquo;ve written and seen plenty of code like the following.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function(a, b, option) {
    option = option || {};
    // ...
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I have and still write code like this. This code is wrong. If a falsy value is passed to the function for &lt;code&gt;option&lt;/code&gt; then the wrong thing happens. We should be writing the following.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function(a, b, option) {
    option = arguments.length &amp;gt; 2 ? option : {};
    // ...
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Although this code expresses the intended thought of setting a default value if an actual parameter for &lt;code&gt;option&lt;/code&gt; is not supplied, it is too verbose and less readable. The reader must count to determine which variable is has index 2. Beyond the awkwardness, the correct version is more difficult to maintain. It is easy to produce the following buggy code if the &lt;code&gt;b&lt;/code&gt; parameter is removed.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function(a, option) {
    option = arguments.length &amp;gt; 2 ? option : {};
    // ...
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If your application uses optional parameters with default values, some new syntax would be beneficial for you.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function(a, b, option = {}) {
    // ...
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The addition of this new syntax tunes the language better to your application&amp;rsquo;s needs.&lt;/p&gt;


&lt;h3&gt;Let&lt;/h3&gt;

&lt;p&gt;Does the following buggy code look familiar?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;for (var i=0, ilen=elements.length; i&amp;lt;ilen; i++) {
    var element = elements[i];
    LIB_addEventListener(element, 'click', function(event) {
        alert('I was originally number ' + i);
    });
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All the elements were the same number?! The solution is to use an immediately evaluated function expression so each alert reports a different number. This is the &amp;ldquo;let&amp;rdquo; idiom after Lisp&amp;rsquo;s various &lt;code&gt;let&lt;/code&gt; forms.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;for (var i=0, ilen=elements.length; i&amp;lt;ilen; i++) {
    var element = elements[i];
    (function(num) {
        LIB_addEventListener(element, 'click', function(event) {
            alert('I was originally number ' + num);
        });
    }(i));
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Sure sometimes delegate listeners might be better than the above code but sometimes the above code is the desired idea. In the above case, we are trying to bind the order of the elements when the loop runs. This order could be lost with the delegate pattern if the elements are rearranged in the DOM.&lt;/p&gt;

&lt;p&gt;This syntax is particularly awkward because of the distance between the formal &lt;code&gt;num&lt;/code&gt; and actual &lt;code&gt;i&lt;/code&gt; parameters of the immediate function.&lt;/p&gt;

&lt;p&gt;The immediate function could be factored out to another location and called inside the loop.&lt;/p&gt;
    
&lt;pre&gt;&lt;code&gt;function attachListener(element, num) {
    LIB_addEventListener(element, 'click', function(event) {
        alert('I was originally number ' + num);
    });
}
for (var i=0, ilen=elements.length; i&amp;lt;ilen; i++) {
    attachListener(elements[i], i);
}&lt;/code&gt;&lt;/pre&gt;
   
&lt;p&gt;Even with this option, sometimes programmers still use the immediate function because it conveys better their intended message to readers.&lt;/p&gt;  
 
&lt;p&gt;If your application uses the let idiom, wouldn&amp;rsquo;t it be nice to have new syntax for it?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;for (var i=0, ilen=elements.length; i&amp;lt;ilen; i++) {
    var element = elements[i];
    let (num = i) {
        LIB_addEventListener(element, function(event) {
            alert('I was originally number ' + num);
        });
    };
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With &lt;code&gt;num&lt;/code&gt; and &lt;code&gt;i&lt;/code&gt; together it is much easier to read this code and a new scope containing &lt;code&gt;new&lt;/code&gt; has been introduced so the closure works properly. Once again, the addition of new syntax can tune the language better to your application&amp;rsquo;s needs.&lt;/p&gt;


&lt;h3&gt;Modules&lt;/h3&gt;

&lt;p&gt;One of the most common idioms in JavaScript programs we all know and love is usually called &amp;ldquo;the module pattern.&amp;rdquo; This idiom provides the benefits of encapsulated variables that are private to the module and imparts sanity to our code.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var event = (function() {

    // private variables
    var listeners = [];
   
    function addEventListener(f) {
        listeners.push(f);
    }

    function clearEventListeners() {
        listeners = [];
    }
    
    // ...
    
    // export the module's API
    return {
        addEventListener: addEventListener,
        clearEventListeners: clearEventListeners
        // ...
    };
}());&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The goal of encapsulation here isn&amp;rsquo;t security. It is to ensure that other developers keep their dirty, monkey-patching hands off your module&amp;rsquo;s data.&lt;/p&gt;

&lt;p&gt;The exporting can be done a few ways but no matter which way there is some boiler plate.&lt;/p&gt;

&lt;p&gt;Importing is verbose also&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function() {

    // import desired properties of the event module
    var addEventListener = event.addEventListener;
    var clearEventListeners = event.clearEventListeners;
    
    // ...
}());&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Some new syntax would be nice to convey the intent of the module pattern better.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module event {
    
    // private variables
    var listeners = [];
   
    export function addEventListener(f) {
        listeners.push(f);
    }

    export function clearEventListeners() {
        listeners = [];
    }
    
    // ...
}&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code&gt;(function() {

    import event;
    
    // ...
}());&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The module pattern is almost everywhere and some new syntax to better express this idiom would better tune the language to all of our applications.&lt;/p&gt;


&lt;h3&gt;Inheritance&lt;/h3&gt;

&lt;p&gt;These idiom examples have been growing in how they each span an increasing number of lines of code. The JavaScript idiom that potentially spans the most lines of your program may be the inheritance idiom.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Employee(first, last, position) {
    // call the superclass constructor
    Person.call(this, first, last);
    this.position = position;
};
// inherit from Person
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

// define an overridding toString() method
Employee.prototype.toString = function() {
    // call superclass's overridden toString() method
    return Person.prototype.toString.call(this) +
           ' is a ' + this.position;
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What a mess. Yes JavaScript makes single inheritance like this possible by linking prototypes but it takes a lot of code to manually make super things happen they way you might like inheritance to work.&lt;/p&gt;

&lt;p&gt;If there could be a maintenance nightmare that is it. The strings &amp;ldquo;Person&amp;rdquo; and &amp;ldquo;Employee&amp;rdquo; are sprawled throughout the code for the Employee &amp;ldquo;class&amp;rdquo;.&lt;/p&gt;

&lt;p&gt;If classes with inheritance are a big part of your application, some syntax would really help clean up the code. Perhaps something like the following.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Employee extends Person {
    constructor(first, last, position) {
        super(first, last);
        public position = position;
    }
 
    update(camera) {
        return super.update() + ' is a ' + position;
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That is a major improvement.&lt;/p&gt;


&lt;h3&gt;Learning from Idioms&lt;/h3&gt;

&lt;p&gt;These common idioms make it clear that JavaScript could use some new syntax for several reasons. The ability to do what we want is usually in JavaScript somewhere. The verbosity of the idioms is sometimes too much. We cut corners. Sometimes we avoid certain algorithms because the idioms are too verbose. The idioms are not self explanatory. They are inside secrets of the community and the intent is not easily recognized by outsiders.&lt;/p&gt;

&lt;p&gt;The ECMAScript committee has recognized that the above idioms, and others idioms, are common across a wide variety of applications. There are proposals for all of these syntax cases in Harmony. Some of them may make it into the next version of ECMAScript and into the browsers for your use. If new syntax gets there eventually then you can use use it.&lt;/p&gt;

&lt;p&gt;Idioms may have emerged in &lt;em&gt;your&lt;/em&gt; application that do not appear in a wide variety of applications. For example, Node.js&amp;rsquo;s non-blocking I/O and heavy reliance on callbacks will undoubtedly result in idioms that do not appear in browser scripts. Syntax specific to just your applications will likely never make it into ECMAScript.&lt;/p&gt;

&lt;p&gt;If you would like to use specialized syntax for the general idioms like those shown above or you would like syntax for your own idioms, what can you do?&lt;/p&gt;


&lt;h2&gt;If Only We Had Macros&lt;/h2&gt;

&lt;p&gt;Lisp languages have had full-blown macros for decades. Through macros, Lisp gives programmers the ability to tune the language&amp;rsquo;s syntax to best match their own applications. Because of its macros, Lisp has been described as &amp;ldquo;the programmable programming language.&amp;rdquo; Powerful stuff.&lt;/p&gt;

&lt;p&gt;Lisp&amp;rsquo;s s-expression syntax, you know, the syntax with all those parens, gives the language a special property called homoiconicity. It roughly means the syntax of the language is also the syntax of its data structures or that a program&amp;rsquo;s parse tree uses the languages data structures. This homoiconicity makes Lisp&amp;rsquo;s macros possible.&lt;/p&gt;

&lt;p&gt;JavaScript doesn&amp;rsquo;t have macros. A major reason for this is that adding macros to languages with C-like syntax, languages that are not homoiconic, is still a research topic. Excerpts from a short conversation on Twitter with littlecalculist, Dave Herman, Ph.D., ECMAScript committee member, and Mozilla Researcher:&lt;/p&gt;

&lt;blockquote&gt;
    &lt;dl&gt;
        &lt;dt&gt;@petermichaux&lt;/dt&gt;
        &lt;dd&gt;I believe @littlecalculist knows more about the research and possibilities for macros in ECMAScript. I&amp;rsquo;d like to know more also.&lt;/dd&gt;
        
        &lt;dt&gt;@littlecalculist&lt;dt&gt;
        &lt;dd&gt;I have thoughts on it for sure. But macros for non-sexp languages is still very much a challenging research topic&lt;/dd&gt;

        &lt;dt&gt;@petermichaux&lt;dt&gt;
        &lt;dd&gt;[...] We&amp;rsquo;ll turn blue waiting for macros.&lt;/dd&gt;

        &lt;dt&gt;@littlecalculist&lt;dt&gt;
        &lt;dd&gt;Might I suggest you keep breathing? ;-) Seriously, I do hope to try, but trust me, macro system design is hard.&lt;/dd&gt;
    &lt;/dl&gt;
&lt;/blockquote&gt;

&lt;p&gt;The message is pretty clear. JavaScript macros are not just around the corner.&lt;/p&gt;


&lt;h2&gt;Harmony Syntax ETA&lt;/h2&gt;

&lt;p&gt;Perhaps the syntax extensions in Harmony are all you dream of and more. If Harmony becomes ECMAScript&amp;nbsp;6 and ECMAScript&amp;nbsp;6 becomes ubiquitous then you&amp;rsquo;ll be all set. So all you need to do is wait...patiently.&lt;/p&gt;

&lt;p&gt;First, let&amp;rsquo;s look at browser adoption. Unfortunately I&amp;rsquo;ll pick on Internet Explorer a bit, which has almost become a cliche, but not because I have something against the Internet Explorer development team at Microsoft or the newest versions of Internet Explorer. It is necessary to look at this browser because it is perhaps the most important case study for estimating when features will be available for all visitors to your web site.&lt;/p&gt;

&lt;p&gt;As of May 2011, &lt;a href=&quot;http://www.w3schools.com/browsers/browsers_stats.asp&quot;&gt;w3schools&lt;/a&gt;, which has relatively tech-savvy visitors, reports Internet Explorer&amp;nbsp;6 still has 2.4% market share. &lt;a href=&quot;http://marketshare.hitslink.com/browser-market-share.aspx?spider=1&amp;amp;qprid=2&quot;&gt;Net Market Share&lt;/a&gt; reports Internet Explorer&amp;nbsp;6 still has 10.36% market share. Your site probably has a market share somewhere between those two numbers but this browser is still hanging on even though it was superseded by Internet Explorer&amp;nbsp;7 in November 2006. How many people are still using Internet Explorer&amp;nbsp;6 or 7? The w3schools site shows 7.7% and Net Market Share shows 18.2%. These browsers just aren&amp;rsquo;t going away fast enough. A publicly available site (e.g. Amazon) cannot afford to ignore market share numbers this large.&lt;/p&gt;
    
&lt;p&gt;There is no point in spending any energy moaning that users should upgrade their browsers or that &amp;ldquo;IE should die!&amp;rdquo; It won&amp;rsquo;t happen. I don&amp;rsquo;t know if it is true but someone once said to me &amp;ldquo;Internet Explorer users upgrade their browser when they upgrade their hardware.&amp;rdquo; For the past few years, hardware has certainly become sufficient that people don&amp;rsquo;t need to upgrade anything to use email, Facebook, Twitter, etc.&lt;/p&gt;

&lt;p&gt;Suppose your web app is sufficiently advanced that you&amp;rsquo;ve decided that you only care about users with &amp;ldquo;modern&amp;rdquo; browsers. Google Apps recently announced that on August 1, 2011 they will stop supporting Internet Explorer&amp;nbsp;7. That is almost 5 years after Internet Explorer&amp;nbsp;7 was released.&lt;/p&gt;
    
&lt;p&gt;Now think about this: Internet Explorer&amp;nbsp;10 is not out yet but, of course, even it won&amp;rsquo;t have Harmony&amp;rsquo;s syntax extensions. Let&amp;rsquo;s estimate that Harmony is approved as ECMAScript&amp;nbsp;6 in mid-2012 and Internet Explorer&amp;nbsp;11 is released in early 2013 with support for all of Harmony&amp;rsquo;s syntax. Five years after that, in 2018, the Google Apps team can drop support for Internet Explorer&amp;nbsp;11 and finally use Harmony syntax freely. (On August 1, 2011, they are also dropping support for the four-year-old Safari&amp;nbsp;3 and two-year-old Firefox&amp;nbsp;3.5 so the waits are still long-ish for other browsers too.)&lt;/p&gt;

&lt;p&gt;Amazon developers might need to wait an additional 5&amp;nbsp;years before they can use Harmony syntax. That&amp;rsquo;s 2023!&lt;/p&gt;

&lt;p&gt;Will you be satisfied waiting 7-12&amp;nbsp;years before you can start using syntax that would be helpful developing your web apps today? Being more optimistic, even if the wait is just 5&amp;nbsp;years, will you wait?&lt;/p&gt;


&lt;h2&gt;JavaScript is Dead.&lt;/h2&gt;

&lt;p&gt;Cause of death: semicolon cancer.&lt;/p&gt;

&lt;p&gt;Perhaps due to JavaScript&amp;rsquo;s syntax alone, JavaScript does not have macros now and won&amp;rsquo;t have them soon if ever. Millions of programmers use JavaScript now and plenty of them are tired or tiring of the verbose idioms confronting them daily. They want new syntax now and won&amp;rsquo;t wait. For this growing group of developers, JavaScript the source code language is dead.&lt;/p&gt;

&lt;p&gt;You had a good reign, JavaScript. We had some good times and wrote some cool apps together. May you rest in peace.&lt;/p&gt;


&lt;h2&gt;Long Live JavaScript!&lt;/h2&gt;

&lt;p&gt;Programmers like to control their own destiny and they are taking action. You can have all the new syntax you want for your browser scripts, right now, if you write in another source language and compile to the ECMAScript&amp;nbsp;3 dialect of JavaScript for the billions of browsers in the wild. By compiling to ECMAScript&amp;nbsp;3 you are completely freed from JavaScript&amp;rsquo;s syntactic evolution. As an added bonus, you can even &lt;em&gt;fix&lt;/em&gt; some of JavaScript&amp;rsquo;s semantic gotchas with a sufficiently sophisticated compiler. JavaScript&amp;rsquo;s new life is as a compilation target.&lt;/p&gt;


&lt;h2&gt;Languages that Compile to JavaScript&lt;/h2&gt;

&lt;p&gt;There have been compilers to JavaScript for years now. In 2007, I started collecting a list of languages with compilers to JavaScript. There were JavaScript extension languages: the now-defunct ECMAScript&amp;nbsp;4, Narrative JavaScript, and Objective-J. There were pre-existing languages: Scheme, Common Lisp, Smalltalk, Ruby, Python, Java, C#, Haskell, etc. There were even brand new languages HaXe, Milescript, Links, Flapjax that were designed to address web programming needs.&lt;/p&gt;

&lt;p&gt;Of these compiler projects, Google&amp;rsquo;s GWT Java-to-JavaScript compiler has probably been the most successful but I don&amp;rsquo;t see programmers who first learned a language other than Java rushing to use Java as their source code language. In fact, none of these compiler projects have accrued a significant long-term user base. At least in the parts of the web that I frequent, with the exception of GWT, it is rare to read about programmers using these compilers for any real projects. There are several legitimate reasons not to use one of these compilers.&lt;/p&gt;

&lt;p&gt;Imagine you build a big project using one of these compilers and part way through find a bug in the compiler. The one maintainer of the compiler may have lost interest or time. Do you want to maintain a compiler? Does anyone on your team have the skills to do that? That ulcer is going to get pretty big while you prepare to explain to the CEO that you now need to rewrite the UI in JavaScript.&lt;/p&gt;

&lt;p&gt;Just the thought of debugging compiled code when a production bug is filed makes my stomach churn. Core dump. What line number in the source code matches the line number Firebug is reporting for the compiled code? HURRY! That bug needs to be fixed now!!!!&lt;/p&gt;

&lt;p&gt;You&amp;rsquo;ve used Objective-J for a big project and now you need to hire a new good programmer. What are your chances of finding the right person? They are probably very low. Just finding an available JavaScript programmer is difficult enough. If you use one of these alternate languages, it is very likely you&amp;rsquo;ll need to train each new person you add to your team.&lt;/p&gt;

&lt;p&gt;Even without these compiler projects being wildly successful, the list of languages that compile to JavaScript has continued to grow. There is no doubt that writing a to-JavaScript compiler is a very cool project. Please pay me to write one.&lt;/p&gt;

&lt;p&gt;There is one notable new entry in the list of languages that compile to JavaScript that is actually causing a big stir and is possibly changing the game for good.&lt;/p&gt;


&lt;h3&gt;CoffeeScript&lt;/h3&gt;

&lt;p&gt;I can tell you right now, I don&amp;rsquo;t know why CoffeeScript has the magic combination of features to garner the attention it has when other projects have failed. Significant whitespace and arrow function syntax. My gut reaction is yuck. There is plenty of things to like: default parameter values, rest parameters, spread, destructuring, fixing the whole implied global mess, even classes if you&amp;rsquo;re into that kind of thing and more. Many of CoffeeScript&amp;rsquo;s features are part of Harmony and so may be in browsers sometime in the future but if you use CoffeeScript then you can have them now. There is nothing like instant gratification.&lt;/p&gt;

&lt;p&gt;Programmers are bursting with affection for CoffeeScript.&lt;/p&gt;

&lt;blockquote&gt;
    &lt;dl&gt;
        &lt;dt&gt;@pyronicide&lt;/dt&gt;
        &lt;dd&gt;Being able to use default values for function arguments in #coffeescript makes me immensely happy.&lt;/dd&gt;
    &lt;/dl&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
    &lt;dl&gt;
        &lt;dt&gt;@_jdpage&lt;/dt&gt;
        &lt;dd&gt;CoffeeScript is wonderful. Now I am spoiled and will complain whenever I have to write JavaScript instead.&lt;/dd&gt;
    &lt;/dl&gt;
&lt;/blockquote&gt;

&lt;p&gt;At the TXJS 2011 conference, Douglas Crockford apparently shared that he thinks &amp;ldquo;CoffeeScript is clearly good stuff.&amp;rdquo;&lt;/p&gt;

&lt;p&gt;There is one aspect of the CoffeeScript project that I really like and it is summed up by the following two quotations. The first comes from Trevor Burnham, author of &lt;a href=&quot;http://pragprog.com/titles/tbcoffee/coffeescript&quot;&gt;CoffeeScript: Accelerated JavaScript Development&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
    &lt;dl&gt;
        &lt;dt&gt;@trevorburnham&lt;/dt&gt;
        &lt;dd&gt;[...] It&amp;rsquo;s not about turning JS into Ruby/Python; it&amp;rsquo;s about having a syntax better suited to JavaScript&amp;rsquo;s inner goodness.&lt;/dd&gt;
    &lt;/dl&gt;
&lt;/blockquote&gt;

&lt;p&gt;The second is from &lt;a href=&quot;http://arcturo.com/library/coffeescript/00_introduction.html&quot;&gt;The Little Book on CoffeeScript&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
    &lt;p&gt;CoffeeScript neatly sidesteps these [JavaScript issues], by only exposing a curated selection of JavaScript features.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The attitude expressed in these quotations really is great and genius marketing too. It is not CoffeeScript verse JavaScript. It is CoffeeScript enhancing the JavaScript programming experience. Could some different syntax and a restricted subset of JavaScript&amp;rsquo;s features really be better than plain old JavaScript?&lt;/p&gt;

&lt;p&gt;Douglas Crockford seems to think so. For years, his &lt;a href=&quot;http://jslint.com/&quot;&gt;JSLint&lt;/a&gt; has been hurting our feelings and demanding that we use very specific whitespace and syntax and that we avoid dangerous JavaScript features. Source code that passes JSLint has access to a true subset of JavaScript: the subset that he calls &amp;ldquo;the good parts.&amp;rdquo; This dialect of JavaScript deserves a name. Maybe GoodScript? After all, you are only allowed to use JSLint for good and not for evil.&lt;/p&gt;

&lt;p&gt;The ECMAScript committee also thinks this is a good idea. The &lt;code&gt;&quot;use strict&quot;&lt;/code&gt; pragma introduced in ECMAScript&amp;nbsp;5 not only restricts some language features like &lt;code&gt;with&lt;/code&gt;, strict mode even changes/fixes the semantics of some parts of the language. Because of the semantic changes, ECMAScript&amp;nbsp;5 strict is a different language or at least a different dialect than ECMAScript&amp;nbsp;5 non-strict.&lt;/p&gt;

&lt;p&gt;CoffeeScript, GoodScript, and ECMAScript&amp;nbsp;5 strict share common goals of keeping you away from the dangerous parts of JavaScript while giving you access to the valuable, safe parts. Each enforces these goals differently but they are enforced one way or another. You don&amp;rsquo;t get new syntax with GoodScript. It is already JavaScript and ready for the browser. You don&amp;rsquo;t get to use ECMAScript&amp;nbsp;5 strict because it is not available in all browsers yet and won&amp;rsquo;t be for years.&lt;/p&gt;

&lt;p&gt;So CoffeeScript seems to be targeting a particular need of web development and maybe that is something other to-JavaScript compilers haven&amp;rsquo;t done or haven&amp;rsquo;t done well before.&lt;/p&gt;

&lt;p&gt;CoffeeScript is also a reasonably thin skin over JavaScript. One consequence of this is that the compiled JavaScript code is reasonably easy to read and not brutal to debug (so I&amp;rsquo;m told.) This reduced debugging fear is contributing to interest in CoffeeScript.&lt;/p&gt;

&lt;p&gt;CoffeeScript almost feels like a set of macros for writing JavaScript programs.&lt;/p&gt;

&lt;p&gt;Since CoffeeScript compilers are in the hands of developers rather than the visitors to sites, you control which version of CoffeeScript you are using. You can upgrade at will. This also means CoffeeScript does not need to be standardized and go through the subsequent painfully slow growth of a standardized language. CoffeeScript can grow at the rate of its community&amp;rsquo;s imagination and desire. JavaScript standardization was essential to the success of the web but the same constraints do not apply to CoffeeScript.&lt;/p&gt;


&lt;h2&gt;Well then I&amp;rsquo;m going to invent my own language.&lt;/h2&gt;

&lt;p&gt;You can do this and it would be a great exercise. You&amp;rsquo;ll be able to call yourself a compiler writer which is pretty darned prestigious.&lt;/p&gt;

&lt;p&gt;The danger of inventing your own language lies in the thinking that you can do better than JavaScript has done &lt;strong&gt;in the long run&lt;/strong&gt;. Language design is hard and I bet your language will grow its share of unsightly hairs. Maybe not as many hairs as JavaScript but still. CoffeeScript hasn&amp;rsquo;t hit puberty yet but there are already signs that hair follicles may exist.&lt;/p&gt;

&lt;blockquote&gt;
    &lt;dl&gt;
        &lt;dt&gt;@maxsamukha&lt;/dt&gt;
        &lt;dd&gt;CoffeeScript: The way variables in outer scopes can be accidentally overwritten is fishy. How bad is it in practice?&lt;/dd&gt;
    &lt;/dl&gt;
&lt;/blockquote&gt;

&lt;p&gt;You were so proud that your simple, readable compiled code was easy to debug. That will become harder as you realize the compiled code&amp;rsquo;s semantics aren&amp;rsquo;t quite what they were supposed to be in corner cases.&lt;/p&gt;
    
&lt;p&gt;Idioms will appear in your language and someone will fork your compiler to do away with those idioms (unless your language happens to have macros.)&lt;/p&gt;

&lt;p&gt;Enough with this nay saying. Go and write your own language right now. You&amp;rsquo;ll be a better programmer for it.&lt;/p&gt;


&lt;h2&gt;What&amp;rsquo;s missing from JavaScript the target language?&lt;/h2&gt;

&lt;p&gt;JavaScript is embarking on a new life as a compilation target. It is a capable target for many language features but it could use improvement. In his &lt;a href=&quot;http://brendaneich.com/2011/05/my-jsconf-us-presentation/&quot;&gt;JSConf.US talk&lt;/a&gt;, Brendan Eich stated that one the goals for Harmony is to be a better target for to-JavaScript compilers.&lt;/p&gt;

&lt;p&gt;Compiled JavaScript can run slower than hand-written JavaScript just like compiled C can be slower than hand-written Assembly (though not always.) Some inefficiency in compiled JavaScript is tolerable because JavaScript virtual machines are fast and the DOM is the bottleneck anyway. That said, some potential source code languages have semantics sufficiently far from JavaScript&amp;rsquo;s semantics that the compiled code is so inefficient that it cannot realistically be used in production web apps. There are already features in Harmony that will enable some of these languages to be compiled to efficient code and thus make these viable source code languages.&lt;/p&gt;


&lt;h3&gt;Proper Tail Calls&lt;/h3&gt;

&lt;p&gt;Programs in Lisp languages depend heavily on recursive calls to properly tail recursive procedures. The &lt;a href=&quot;http://wiki.ecmascript.org/doku.php?id=harmony:proper_tail_calls&amp;amp;s=const&quot;&gt;proper tail calls&lt;/a&gt; proposal in Harmony will allow these programs to be compiled to JavaScript without the inefficient trampoline technique currently necessary to avoid overflowing the call stack. Awesome! Let&amp;rsquo;s look at that in a bit more detail.&lt;/p&gt;

&lt;p&gt;The following JavaScript is an example of mutually recursive functions which would work fine in Lisp but since JavaScript currently does not have proper tail calls, will overflow the JavaScript call stack when &lt;code&gt;number&lt;/code&gt; is large.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function isEven(number) {
    if (number === 0) {
        return true;
    }
    else {
        return isOdd(number - 1);
    }
}

function isOdd(number) {
    if (number === 0) {
        return false;
    }
    else {
        return isEven(number - 1);
    }
}

isEven(100000); // InternalError: too much recursion&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the above code, a call to &lt;code&gt;isEven(100000)&lt;/code&gt; isn&amp;rsquo;t complete and removed from the call stack until &lt;code&gt;isOdd(99999)&lt;/code&gt; returns which isn&amp;rsquo;t complete and removed from the call stack until &lt;code&gt;isEven(99998)&lt;/code&gt; returns and so on. That&amp;rsquo;s a lot of calls on the call stack! And there is no need for them all to be on the call stack. &lt;code&gt;isEven(100000)&lt;/code&gt; doesn&amp;rsquo;t have anything intelligent remaining to do once it calls &lt;code&gt;isOdd(99999)&lt;/code&gt; because the call to &lt;code&gt;isOdd(99999)&lt;/code&gt; is the very last thing in &lt;code&gt;isEven(100000)&lt;/code&gt;. The call is said to be in tail position. &lt;code&gt;isEven(100000)&lt;/code&gt; is just waiting to return the value returned by &lt;code&gt;isOdd(99999)&lt;/code&gt; and a clever language can just pop &lt;code&gt;isEven(100000)&lt;/code&gt; off the call stack and replace it with the call to &lt;code&gt;isOdd(99999)&lt;/code&gt; thus saving space on the call stack.&lt;/p&gt; 

&lt;p&gt;With trampolines we can ensure that even in JavaScript the call stack doesn&amp;rsquo;t grow large. The following is just a sketch of how trampolines might be implemented and how &lt;code&gt;isEven&lt;/code&gt; and &lt;code&gt;isOdd&lt;/code&gt; might be compiled for a JavaScript interpreter that doesn&amp;rsquo;t have proper tail calls.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function bounce(ret) {
    while (typeof ret === 'function') {
        ret = ret();
    }
    return ret;
}

function isEven(number) {
    if (number === 0) {
        return true;
    }
    else {
        return function() {
            return isOdd(number - 1);
        };
    }
}

function isOdd(number) {
    if (number === 0) {
        return false;
    }
    else {
        return function() {
            return isEven(number - 1);
        };
    }
}

bounce(function() {return isEven(100000);}); // true&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can see the extra overhead of the &lt;code&gt;bounce&lt;/code&gt; function which implements the trampoline calls is quite onerous. It creates closures for each continuation, doubles the number of calls, and must examine the returned value after each bounce; however, &lt;code&gt;isEven(10000)&lt;/code&gt; does complete and is removed from the callstack &lt;em&gt;before&lt;/em&gt; &lt;code&gt;isOdd(99999)&lt;/code&gt; is called. The full computation completes in constant call stack space.&lt;/p&gt;

&lt;p&gt;The bottom line is trampolines incur too much overhead. They incur so much overhead that when Rich Hickey created Clojure, his Lisp for the JVM, he decided his language could not have proper tail calls because trampolines were too expensive. That must have been a painful decision for someone who loves the Lisp family of languages.&lt;/p&gt;

&lt;p&gt;The good news is that the ECMAScript committee has recognized this deficiency in JavaScript and has added proper tail calls to Harmony. This will benefit programmers writing directly in JavaScript and developers of to-JavaScript compilers.&lt;/p&gt;


&lt;h3&gt;Lambdas&lt;/h3&gt;

&lt;p&gt;Another strawman proposal not yet promoted to Harmony is the &lt;a href=&quot;http://wiki.ecmascript.org/doku.php?id=strawman:block_lambda_revival&quot;&gt;Block Lambda Revival&lt;/a&gt; which combines some new syntax with a new language construct called a lambda. A lambda is a callable thing, like a function, but it obeys Tennent&amp;rsquo;s Correspondence Principle. Tennent&amp;rsquo;s Correspondence Principle states that wrapping an expression or block of code in an immediate lambda should not change the meaning of that wrapped code. JavaScript functions are not lambdas and do not obey Tennent&amp;rsquo;s Correspondence Principle. For example,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function one() {
    return 1;
}

one(); // 1&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;is not the same when the return line is wrapped in an immediate function&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function one() {
    (function() {
        return 1;
    }());
}

one(); // undefined&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The syntax of the block lambda proposal for a lambda that takes two arguments and sums them is &lt;code&gt;{|a,&amp;nbsp;b|&amp;nbsp;a&amp;nbsp;+&amp;nbsp;b}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Using the syntax of the block lambda proposal  we can wrap the return line in an immediate lambda without changing the meaning.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function one() {
    ({||
        return 1;
    }());
}

one(); // 1&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Thanks to lambdas obeying Tennent&amp;rsquo;s Correspondence Principle, the &lt;code&gt;return&lt;/code&gt; still means return from the function &lt;code&gt;one&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You may ask &amp;ldquo;Who cares about this computer science-y stuff?&amp;rdquo; to which I reply &amp;ldquo;Did any of that macro business seem useful?&amp;rdquo; because lambdas are a fundamental building block in the code generated by many macros. And since lambdas play nicely with JavaScript&amp;rsquo;s &lt;code&gt;return&lt;/code&gt;, &lt;code&gt;arguments&lt;/code&gt;, and &lt;code&gt;this&lt;/code&gt;, lambdas would be a valuable addition to the language for compiler writers.&lt;/p&gt;

&lt;p&gt;I&amp;rsquo;m focusing on the JavaScript-as-a-target aspect of the block lambda proposal. If you plan on writing in JavaScript forever after, the proposal has other benefits for you too that don&amp;rsquo;t matter to compiler writers.&lt;/p&gt;

&lt;p&gt;The block lambda strawman has not yet been promoted to Harmony and so currently doesn&amp;rsquo;t have a path into ECMAScript&amp;nbsp;6 and browsers around the world. The standardization process is slow. Maybe there will be another decade stall in evolving the language like there was after ECMAScript&amp;nbsp;3. Maybe the next edition of ECMAScript will be the last edition. Better to get the best stuff in there than hope to get it in later. If you care about the future of JavaScript and think lambdas would be a benefit to the language then &lt;strong&gt;let the ECMAScript committee know by sending a message to the &lt;a href=&quot;https://mail.mozilla.org/listinfo/es-discuss&quot;&gt;es-discuss mailing list&lt;/a&gt; in support of the block lambda proposal&lt;/strong&gt;. Powerful, orthogonal language features like tail calls and lambdas which have no efficient workarounds may be the most important additions in the next edition of ECMAScript.&lt;/p&gt;


&lt;h2&gt;What&amp;rsquo;s missing from the browser?&lt;/h2&gt;

&lt;p&gt;The browser can help JavaScript succeed in its new life as a compilation target. The browser interprets compiled JavaScript and complains when the compiled code has an error. The error messages contain line numbers in the compiled code but you want to know the line number in source code.&lt;/p&gt;

&lt;p&gt;The Mozilla crowd has &lt;a href=&quot;https://bugzilla.mozilla.org/show_bug.cgi?id=618650&quot;&gt;an open ticket&lt;/a&gt; and &lt;a href=&quot;https://wiki.mozilla.org/DevTools/Features/SourceMap&quot;&gt;a dev tools project&lt;/a&gt; to ease debugging source code by mapping compiled code lines to source code lines. Since you control the browser in which you primarily develop and test, you can use this feature as soon as it is ready.&lt;/p&gt;

&lt;p&gt;Somewhere I read that the Webkit folks are developing similar source code debugging assistance but I cannot find any concrete evidence.&lt;/p&gt;


&lt;h2&gt;Polyglot&lt;/h2&gt;

&lt;p&gt;JavaScript&amp;rsquo;s monopoly in the browser has meant front-end programmers all speak the same language. This has given the community a &lt;i&gt;lingua franca&lt;/i&gt; enabling good communication and code sharing. We are now headed for a polyglot future where you choose the language(s) you want to learn and use for developing browser applications. Maybe you are only using a few JavaScript language extensions via &lt;a href=&quot;http://code.google.com/p/traceur-compiler/&quot;&gt;Traceur&lt;/a&gt; and compiling templates to JavaScript with &lt;a href=&quot;http://mustache.github.com/&quot;&gt;Mustache&lt;/a&gt;. This still means that the CoffeeScript programmer won&amp;rsquo;t understand your source code immediately.&lt;/p&gt;

&lt;p&gt;This divergence was inevitable as it has happened on all previously successful platforms. There have been multiple languages for building native applications almost forever. C is still common but C++, Objective-C, and many other languages are available. The JVM was intended to run programs written in Java but clever developers have added other languages like Clojure and JRuby as options. Microsoft recognized what seems to be a human psychological need for a variety of languages and developed its .NET CLR platform for multiple languages from the beginning. Programs written in Basic, C#, IronPython, etc can all be run on the CLR.&lt;/p&gt;

&lt;p&gt;Barriors to communication in the front-end community are not new anyway. A developer using Dojo cannot immediately understand the source code of an application written with jQuery or YUI. There is a plethora of libraries, some very different, that add the ideas of class-based inheritance to JavaScript. So we already have our barriors even within JavaScript.&lt;/p&gt;

&lt;p&gt;Having multiple source languages will increase the barriers in our community. Programmers will still need to know JavaScript, at least for a while, but in a few years they may know other source languages better then they know JavaScript.&lt;/p&gt;

&lt;p&gt;Choice is a blessing and a curse.&lt;/p&gt;


&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;It is great having the opportunity to watch JavaScript&amp;rsquo;s transition to a new life as it happens. It&amp;rsquo;s impossible to say which languages will end up winning market share in the to-JavaScript compilation but it is sure to be interesting. CoffeeScript is gaining momentum now but I think many other successful source code languages will follow.&lt;/p&gt;

&lt;p&gt;What do you think will happen?&lt;/p&gt;


</content>
</entry>

<entry>
    <id>http://peter.michaux.ca/articles/sicp-classes-for-javascript</id>
    <title>SICP Classes for JavaScript</title>
    <updated>2011-06-05T11:56:00Z</updated>
    <link href="/articles/sicp-classes-for-javascript" rel="alternate" type="text/html"/>
		<content type="html">&lt;p&gt;&lt;strong&gt;Warning:&lt;/strong&gt; This article is intended for JavaScript programmers. Parens are coming but only briefly and you can handle it and it will be good for you.&lt;/p&gt;

&lt;p&gt;In &lt;strong&gt;Structure and Interpretation of Programming Languages Second Edition&lt;/strong&gt; (SICP) on page 182, the authors introduce the idea of &lt;i&gt;message passing&lt;/i&gt; with the following example in Scheme of a complex number constructor function.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define (make-from-real-imag x y)
  (define (dispatch op)
    (cond ((eq? op 'real-part) x)
          ((eq? op 'imag-part) y)
          ((eq? op 'magnitude)
           (sqrt (+ (square x) (square y))))
          ((eq? op 'angle) (atan y x))
          (else
           (error &quot;Uknown op -- MAKE-FROM-REAL-IMAG&quot; op))))
  dispatch)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The important part to note here is that the value returned by the &lt;code&gt;make-from-real-imag&lt;/code&gt; constructor function is actually a dispatch procedure that you can call with a message argument. You can send messages to get the real part or magnitude of the complex number.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define c (make-from-real-imag 3 4))
(c 'real-part) ; 3
(c 'imag-part) ; 4
(c 'magnitude) ; 5
(c 'angle)     ; 0.927295218001612
(c 'asdf)      ; ERROR: Uknown op -- MAKE-FROM-REAL-IMAG: asdf&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;Let&amp;rsquo;s see what the above code looks like in JavaScript, our &lt;i&gt;lingua franca&lt;/i&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function makeFromRealImag(x, y) {
    function dispatch(op) {
        switch (op) {
            case 'realPart': return x;
            case 'imagPart': return y;
            case 'magnitude':
                return Math.sqrt(x*x + y*y);
            case 'angle': return Math.atan2(y, x);
            default:
                throw 'Unknown op -- makeFromRealImag: ' + op;
        }
    }
    return dispatch;
}

var c = makeFromRealImag(3, 4);
c('realPart');  // 3
c('imagPart');  // 4
c('magnitude'); // 5
c('angle');     // 0.9272952180016122
c('asdf');      // &quot;Unknown op -- makeFromRealImag: asdf&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now this probably doesn&amp;rsquo;t look like any object-oriented JavaScript you&amp;rsquo;ve seen before but it illustrates an important point. In JavaScript, we can represent the idea of an object as a function of its messages. The constructor function returns a dispatch function that you wrote that can dispatch any message any way that you want it to. This immediately gives you Spidermonkey&amp;rsquo;s &lt;code&gt;__nosuchmethod__&lt;/code&gt;, Smalltalk&amp;rsquo;s &lt;code&gt;doesNotUnderstand&lt;/code&gt;, and Ruby&amp;rsquo;s &lt;code&gt;method_missing&lt;/code&gt;. Powerful stuff but unfortunately the JavaScript code above runs very slowly. We can move towards a faster and more familiar JavaScript style.&lt;/p&gt;

&lt;p&gt;SICP page 223, introduces the idea of mutable objects but the most interesting point is the variation on the dispatch procedure.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define (make-account balance)
  (define (withdraw amount)
    (if (&gt;= balance amount)
        (begin (set! balance (- balance amount))
               balance)
        &quot;Insufficient funds&quot;))
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  (define (dispatch m)
    (cond ((eq? m 'withdraw) withdraw)
          ((eq? m 'deposit) deposit)
          (else (error &quot;Unknown request -- MAKE-ACCOUNT&quot;
                       m))))
  dispatch)

(define account (make-account 10))
((account 'deposit) 5)  ; 15
((account 'withdraw) 3) ; 12&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Converting this to JavaScript we have the following.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function makeAccount(balance) {
    function withdraw(amount) {
        if (balance &gt;= amount) {
            balance = balance - amount;
            return balance;
        }
        return &quot;Insufficient funds&quot;;
    }
    function deposit(amount) {
        balance = balance + amount;
        return balance;
    }
    function dispatch(m) {
        switch (m) {
            case 'withdraw': return withdraw;
            case 'deposit': return deposit;
            default:
                throw &quot;Unknown request -- makeAccount: &quot; + m;
        }
    }
    return dispatch;
}

var account = makeAccount(10);
account('deposit')(5);  // 15
account('withdraw')(3); // 12&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The way the &lt;code&gt;dispatch&lt;/code&gt; function works for accounts is quite different than in the complex numbers case. In the case of complex numbers, when a message was sent to the &lt;code&gt;dispatch&lt;/code&gt; function, it executed the associated operation (i.e. the method) immediately. In contrast, the account &lt;code&gt;dispatch&lt;/code&gt; function returns the method associated with the message and that method can then be called.&lt;/p&gt;

&lt;p&gt;This is very similar to how JavaScript&amp;rsquo;s &lt;code&gt;reciever.message(arg)&lt;/code&gt; syntax works and we can move to a more familiar object-oriented JavaScript style.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function makeAccount(balance) {
    function withdraw(amount) {
        if (balance &gt;= amount) {
            balance = balance - amount;
            return balance;
        }
        return &quot;Insufficient funds&quot;;
    }
    function deposit(amount) {
        balance = balance + amount;
        return balance;
    }
    return {
      withdraw: withdraw,
      deposit: deposit
    };
}

var account = makeAccount(10);
account.deposit(5);  // 15
account.withdraw(3); // 12&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this last version, we&amp;rsquo;ve stopped writing our own dispatch logic and use JavaScript&amp;rsquo;s built-in property lookup. This increases speed significantly. We&amp;rsquo;ve lost the ability to do the &lt;code&gt;__noSuchMethod__&lt;/code&gt; type of dispatching when using standard ECMAScript but that doesn&amp;rsquo;t seem to be commonly useful anyway.&lt;/p&gt;

&lt;p&gt;For the well-read JavaScript programmers out there, you may recognize this last version as &lt;i&gt;durable objects&lt;/i&gt; from Douglas Crockford&amp;rsquo;s book &lt;strong&gt;JavaScript: The Good Parts&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I find it interesting that the word &amp;ldquo;inheritance&amp;rdquo; does not appear in SICP&amp;rsquo;s index even though the book goes on to implement complex programs like language interpreters and compilers in a message passing style. That shows this simple style of object-oriented programming can take you far.&lt;/p&gt;

&lt;p&gt;The moral of the story is that old books are worth reading and can change the way you program today. You can even &lt;a href=&quot;http://mitpress.mit.edu/sicp/&quot;&gt;read SICP for free&lt;/a&gt;.&lt;/p&gt;


</content>
</entry>


</feed>
