The JavaScript arguments object…and beyond

Spare a thought for JavaScript’s arguments object. It wants so desperately to be an array. It walks like an array, quacks like an array but flies like a turkey. During the early years of the language Brendan Eich came close to rewriting arguments as an array until ECMA came along and clipped its wings forever.

In spite of all this (or maybe because of it) we love the arguments object. In this article I’ll explore its niftyness and its quirkiness and I’ll finish up by looking at the likely successors: rest and spread
Continue reading

Exploring JavaScript for-in loops

The for-in loop is the only cross-browser technique for iterating the properties of generic objects. There’s a bunch of literature about the dangers of using for-in to iterate arrays and when to apply the hasOwnProperty filter, but beyond that, documentation of this ubiquitous construct is surprisingly patchy. This article attempts to fill some gaps, I hope its useful.

Continue reading

Delegation vs Inheritance in JavaScript

When asked what he might do differently if he had to rewrite Java from scratch, James Gosling suggested that he might do away with class inheritance and write a delegation only language.

Using inheritance as a vehicle for code reuse is a bit like ordering a happy meal because you wanted the plastic toy. Sure a circle is a shape and a dog is a mammal – but once we get past those textbook examples most of our hierarchies get arbitrary and tenuous – built for manipulating behaviour even as we pretend we are representing reality. Successive descendants are saddled with an ever increasing number of unexpected or irrelevant behaviours for the sake of re-using a few.

Delegation is a technique that promotes code reuse by allowing runtime function invocation in the context of a specific instance – regardless of the hierarchical lineage of instance and function. JavaScript has excellent support for Delegation in the form of call and apply which lets us inject an object into the this value of any function. This permits unfeterred code sharing, free from the constraints of unwieldy, unnatural and overly complex hierarchies.

I’m going to demonstrate, by way of a use case, how call and apply can promote a clean, functional approach code to re-use. Then I’ll discuss how the ES 5 specification enables re-use of built-in functions by formalizing the concept of generic functions.

Continue reading

Namespacing in JavaScript

Global variables should be reserved for objects that have system-wide relevance and they should be named to avoid ambiguity and minimize the risk of naming collisions. In practice this means you should avoid creating global objects unless they are absolutely necessary.

But, hey, you already knew all that…..

So what do you do about it? Conventional wisdom tells us that the best global abatement strategy is to create a small number of global objects which will serve as de facto namespaces for underlying modules and subsystems. I’m going to explore several approaches to namespacing, culminating in an elegant, safe and flexible solution that I based on a recent article by James Edwards.

Continue reading

JSON and JSONP

(extractos en español)

There’s been an interesting discussion over at JSMentors.com about JSONP and how to make it safer. This is a good thing, not least because it forced me to take a deeper look and come up with a (sort of) counter-proposal of my own.

We’ll start with an overview of JSON basics, including the EcmaScript 5 JSON API, and then discuss cross-domain JSON retrieval via JSONP. Finally I’ll introduce a simple and relatively safe JSONP framework and show how to use it to fetch tweets from the Twitter database.

Continue reading

Extending Objects with JavaScript Getters

Most browsers are coalescing around a consistent API for defining JavaScript Getters and Setters. I’m not entirely comfortable with custom getters and setters – JavaScript’s clean syntax is now a little murkier, and we have a new pitfall to avoid when iterating and cloning object properties, not to mention a significant risk of involuntary recursion – but still I’ll admit they have their uses.
Continue reading

JavaScript’s Dream Team: in praise of split and join

JavaScript is blessed with two remarkably powerful yet under-appreciated methods: split and join act as perfect counterparts. Their symmetry allows JavaScript’s array and string types to enjoy a unique coupling: arrays can easily be serialized to strings and back again, a feature we can leverage to good effect. In a moment we’ll explore some interesting applications – but first some introductions:

Continue reading

Understanding JavaScript Closures

In JavaScript, a closure is a function to which the variables of the surrounding context are bound by reference.

function getMeAClosure() {
    var canYouSeeMe = "here I am";
    return (function theClosure() {
        return {canYouSeeIt: canYouSeeMe ? "yes!": "no"}; 
    });
}

var closure = getMeAClosure();
closure().canYouSeeIt; //"yes!"

Every JavaScript function forms a closure on creation. In a moment I’ll explain why and walk through the process by which closures are created. Then I’ll address some common misconceptions and finish with some practical applications. But first a brief word from our sponsors: JavaScript closures are brought to you by lexical scope and the VariableEnvironment

Continue reading

Rethinking JavaScript for-loops

(versión abreviada en español)

If you think the introduction of Array.prototype.forEach and friends will send the for-loop the way of the dodo, think again. There’s life in the old dog yet.

The for-loop is often seen as something of a one trick pony, most suited to the classic form of list iteration:

for (var i=0; i<arr.length; i++) {
    //do something to each member
}

but with the wealth of higher order functions now available both natively and in frameworks we can just do this (or variants thereof)

arr.forEach(function(each)) {
    //do something to each
});

Ironically as high-order functions gradually render the traditional pattern obsolete, so might we become liberated from our old habits and branch out to explore more interesting patterns of for-looping.

To whet your appetite – here’s an ultra-compact way to generate and alert the first n members of the Fibonacci series:

for (
    var i=2, r=[0,1];
    i<15 || alert(r);
    r.push(r[i-1] + r[i-2]), i++
);
//alerts "0,1,1,2,3,5,8,13,21,34,55,89,144,233,377"

 
Continue reading