JavaScript Best Practices

Scott Sauyet

http://scott.sauyet.com/Javascript/BestPractices/

A Quick Quiz

What happens when you call processArray?


    var displayArrayElements = function(someArray) {
        for (i = 0; i < someArray.length; i++) {
            alert(someArray[i]);
        }
    }
    var processArray = function() {
        var myArray = [[1, 2], [3, 4]];
        for (i = 0; i < myArray.length; i++) {
            displayArrayElements(myArray[i]);
        }
    }

Quiz Answer

It alerts 1, then 2, and quits

 

Why?

First-class citizens

In Java, objects (and maybe their poor cousins, primitives, are the only first-class citizens.

In JavaScript, functions have equal or perhaps even greater importance.



function successFn() {
    alert("Got it!");
}
function errorFn() {
    alert("Failed miserably!");
}

performAjaxCall("GET", myURL, successFn, errorFn);

Call and Apply

You can programmatically call a function:


successFn.call(this, data, errorCode, errorMessage);

Or:


successFn.apply(this, [data, errorCode, errorMessage]);

The difference between the two is that the second takes an array of arguments.

Context

No Methods in JS

JSON

Closures

JavaScript Sample


function selectAllCheckboxes(parent, children) {
    if (!parent || !children) return;
    if (!children.length) return;
    var childClick = (function() { return function(event) {
        var count = 0;
        for (var i = 0; i < children.length; i++) {
            count += children[i].checked ? 1 : 0;
        }
        parent.checked = (count == children.length);
    }})();
    for (var i = 0; i < children.length; i++) {
        dojo.event.connect(children[i], "onclick", childClick);
    }

JavaScript Sample, continued


    var parentClick = (function() {return function (event){
        var element = event.target;
        for(var i=0; i < children.length; i++) {
            children[i].checked = element.checked;
        }
    }})();
    dojo.event.connect(parent, "onclick", parentClick); 
}

Resources