random memes }

Strict mode for Javascript

A small item...

Javascript is a hash (pun not entirely intended). There are good parts to Javascript, and bad parts. For folk attempting to learn Javascript for the first time, they could use some help avoiding the icky bits.

My first cut at rules for a "strict" mode for Javascript:

No doubt I could come up with more rules, with a bit more reflection, but this is a start.

No use of "function name(){}" declarations There are two means of declaring functions, and I strongly prefer the second form. Programmers coming from other languages tend most often to use this form:

function foo() { }

For an entire collection of reasons I prefer this form:

var foo = function() { };

The second form is better suited for later refactoring, and offers subtle emphasis to the learning programmer of the difference offered by Javascript. The first form can also lead to subtle bugs (which I do not want to explain) - certainly not what you need when first learning a rather different language.

As a partial hint, I tend to make rather a lot of use of namespaces, so my function declarations most often look like this:

var ZOT = {}; ZOT.foo = function() { };

Or in the more elaborate use:

var ZOT = (function() { var foo = function() { }; return { foo: foo }; })();

This last form makes full use of closures, and allows for private data and functions.

No use of "document.write()" Programmers tend to want to generate HTML from program code. This is a huge mistake.

To me this is a classic application of separation of concerns. HTML describes page structure. CSS describes page presentation. Script describes dynamic behaviors. Best to keep each concern separate.

No use of "new" On this point I am certain others will differ. They might even be right. Certainly the "new" operator is of huge advantage in static languages. But that is not the domain of Javascript - certainly in the web browser, and possibly even for server-side usage.

The "new" operator misleads programmers when first learning Javascript. The pattern of usage most appropriate to a static-class language is not the same as the most appropriate usage in an entirely dynamic language.

Conflicted over Crockford There is a measure of irony in the last point. Douglas Crockford has consistently served to promote better usage of Javascript. Crockford was hired by Yahoo. The quite elaborate user interface library in Javascript developed by Yahoo, is first invoked with "new YUI()". YUI obviously represents a substantial body of work, at least partially in what seems the right direction. Yet I cannot quite get past the beginning.