js13kGames, simplex-noise.js, Media Chooser, User Message Queue

31 Aug 2012 | By Alex Young | Comments | Tags games competitions services node



js13kGames is a HTML5 and JavaScript game development competition. It’s currently open for entries, and the competition will close on the 13th September 2012. The basic rule states that entries must be less than 13 KB, but please read through all of the rules before entering.

The judges include Michal Budzynski (Firefox OS developer) and Rob Hawkes (Mozilla), and the competition was organised by Andrzej Mazur.


simplex-noise.js (npm: simplex-noise) by Jonas Wagner is a simplex noise implementation, which is often used to generate noise for graphics. The author has posted a plasma demo to jsFiddle.

Media Chooser

Media Chooser (GitHub: chute / media-chooser) from Chute is a client-side library for working with Chute’s media API. Files can be uploaded or selected from social networks like Facebook and Instagram. It’s an extremely simple way of accepting file uploads in a single page application without the traditional server-side requirements.

User Message Queue

User Message Queue (License: MIT) by Robert Murray is a FIFO message queue. It allows messages to be pushed to a queue that will be displayed one after another in a suitable container element. It’s simple and lightweight, so it might work well in combination with a client-side toolkit like Bootstrap.

Optimistic Server Interactions

30 Aug 2012 | By Alex Kessinger | Comments | Tags mobile async
Alex Kessinger is a programmer who lives in the Bay Area. He strives to make websites, cook, and write a little bit better each day. You can find more from Alex at his blog, on App.net, and Google+.

At PicPlz we built a hybrid mobile app. We had a native container written for iOS and Android that hosted a web version of our code. PicPlz was the first time I had worked on a fully mobile website. My operating paradigm was that I was building a website for a small screen.

One day, our iOS developer asked me why our follow button didn’t just react when a user touched it. He pointed out that most iOS apps work that way. It was a glaring reminder that our app was something other than native. I genuinely had never thought about doing it any other way. I was building a web app, and when building web apps there is network IO. For things to be consistent, you need to wait until the network IO has finished. The other engineer persisted though, claiming that it doesn’t have to work that way.

In order to make it feel more native I wrote the code so that the button would activate and change state immediately. If there was an error, which was infrequent, the button would flip back to inform the user. In the other 99.99% of the time the user would feel as if the interaction happened immediately.

Since implementing these interactions in PicPlz I have found out what they are called: Optimistic server interactions. While it is how things work in most mobile applications, it’s not how most things work in web applications. Why? Well, we all know exactly what’s going on when we make a request to a server – nothing is certain unless a response is received. When we see a spinner or a loading bar we understand, but does a user? Do they understand that your web page is making HTTP requests on their behalf, or are they about to click away from your website because it feels slow?

I am sure you might be worried that this approach feels strange from a user experience point of view. Yes, it’s weird, but how often will this happen? If your code is that fragile, then you might have a bigger problem.

Coding Style

There are times when optimistic server interactions are awkward to write. For example, building a chain of such interactions will result in highly indented callbacks.

Despite this, most cases shouldn’t be more complex than the following pseudo-code example:

$('body').on('click', '.favorite', function() {
  var button = $(this);
  $.post('/follow', { 'favorite': true }).fail(function() {
    // flip favorite button to inactive
    // inform user action failed.

Another criticism is that if this happens too often, users will begin to question whether their actions are actually doing anything. This is a valid concern, but as I said earlier if your code really is failing this often then you probably have larger problems.

To be fair, I haven’t really tried this on any major piece of code. This is a trick I use mostly for small interactions like follow or favorite buttons. Web apps like Google Docs are clearly using this type of interaction all the time. Still, this technique is slowly working its way into larger interactions. If you do client-side rendering, then you’re 90% there. You can capture user input and update the interface immediately.

I’d like to thank Mark Storus for providing counter arguments.

Node Roundup: Stream Handbook, Screenshot as a Service, captchagen, Suppose

29 Aug 2012 | By Alex Young | Comments | Tags node modules libraries security unix streams
You can send in your Node projects for review through our contact form or @dailyjs.

Stream Handbook

Stream Handbook by the venerable James Halliday is a guide to streams, a commonly overlooked feature of Node that’s only just starting to get the attention it deserves.

So far James has written a solid introduction to streams, and he’s working on adding more detailed coverage based on Node’s related API methods and objects.

Screenshot as a Service

Screenshot as a Service (GitHub: fzaninotto / screenshot-as-a-service, License: MIT) by Francois Zaninotto is a fork of TJ Holowaychuk’s screenshot-app, which is running at screenshot.etf1.fr. Since forking the app, Francois has worked on making it more robust. It can be used synchronously or asynchronously:

# Take a screenshot
GET /?url=www.google.com

# Asynchronous call
GET /?url=www.google.com&callback=http://www.myservice.com/screenshot/google



captchagen (License: MIT, npm: captchagen) from the team at Fractal is a CAPTCHA image generator. It can generate both a PNG and the corresponding audio through eSpeak.

Images are generated based on a custom algorithm and the Canvas module. Mocha tests have been included.


Suppose (GitHub: jprichardson / node-suppose, License: MIT, npm: suppose) by JP Richardson is a JavaScript version of Expect (man expect). It has a chainable API, so it’s easy to create complex expectations with a familiar syntax:

suppose('npm', ['init'])
  .on(/name\: \([\w|\-]+\)[\s]*/).respond('awesome_package\n')
  .on('version: (0.0.0) ').respond('0.0.1\n')
  .on('description: ').respond("It's an awesome package man!\n")
  .on('entry point: (index.js) ').respond("\n")
  .on('test command: ').respond('npm test\n')
  .on('git repository: ').respond("\n")
  .on('keywords: ').respond('awesome, cool\n')
  .on('author: ').respond('JP Richardson\n')
  .on('license: (BSD) ').respond('MIT\n')
  .on('ok? (yes) ' ).respond('yes\n')

The author has included Mocha tests and examples in the readme file.

jQuery Roundup: jQuery Color 2.1.0, jQuery UI 1.9 RC, Avgrund Modal

28 Aug 2012 | By Alex Young | Comments | Tags jquery plugins jqueryui effects
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery Color 2.1.0

jQuery Color 2.1.0 (GitHub: jquery / jquery-color, License: MIT) has been released. This plugin includes lots of methods for defining, parsing, and otherwise manipulating and animating colours. Version 2 includes new API methods that allow colours to be created and modified, and this includes support for RGBA and HSLA colours and animations.

Here are some examples of the plugin in use:

// String colour parsing

// RGB
$.Color(255, 0, 0);

$.Color(255, 0, 0, 0.8);

// Objects work as well
$.Color({ red: red, green: green, blue: blue, alpha: alpha });

// Getters and setters
$.Color(255, 100, 130)
  .green(); // 101

// Conversion
$.Color(255, 100, 130).toRgbaString(); // 'rgb(255,100,130)'

jQuery UI 1.9 RC

jQuery UI 1.9 RC has been released, and updates jQuery to 1.8 and jQuery Color to the 2.0 series. The jQuery UI team are also working on upgrading the project’s infrastructure:

We’re working on a new web site, new download builder, and new documentation site to accompany the new release.

Avgrund Modal


Avgrund Modal (GitHub: voronianski / jquery.avgrund.js, License: MIT) by Dmitri Voronianski is a modal plugin that attempts to create the impression of depth as the modal appears on the page. The main content zooms out as the modal appears – the overall effect is surprisingly slick. Basic usage is $(selector).avgrund(), but the plugin has lots of options:

  width: 380
, height: 280
, showClose: false
, showCloseText: ''
, holderClass: ''
, overlayClass: ''
, enableStackAnimation: false
, template: 'Your content goes here..'

This plugin is based on the Avgrund concept by Hakim El Hattab.

JS101: Equality

27 Aug 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

There are four equality operators in JavaScript:

  • Equals: ==
  • Not equal: !=
  • Strict equal: ===
  • Strict not equal: !==

In JavaScript: The Good Parts, Douglas Crockford advises against using == and !=:

My advice is to never use the evil twins. Instead, always use === and !==.

The result of the equals operator is calculated based on The Abstract Equality Comparison Algorithm. This can lead to confusing results, and these examples are often cited:

'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == undefined  // false
false == null       // false
null == undefined   // true

Fortunately, we can look at the algorithm to better understand these results. The first example is false due to this rule:

If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.

Basically, the sequence of strings is not the same. In the second example, the types are different, so this rule is used:

If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

This is where the behaviour of the == starts to get seriously gnarly: behind the scenes, values and objects are changed to different types. The equality operator always tries to compare primitive values, whereas the strict equality operator will return false if the two values are not the same type. For reference, the underlying mechanism used by the strict equality operator is documented in the The Strict Equality Comparison Algorithm section in the ECMAScript Specification.

Strict Equality Examples

Using the same example with the strict equality operator shows an arguably more intuitive result:

'' === '0'           // false
0 === ''             // false
0 === '0'            // false

false === undefined  // false
false === null       // false
null === undefined   // false

Is this really how professional JavaScript developers write code? And if so, does === get used that often? Take a look at ajax.js from jQuery’s source:

executeOnly = ( structure === prefilters );
if ( typeof selection === "string" ) {
} else if ( params && typeof params === "object" ) {

The strict equality operator is used almost everywhere, apart from here:

if ( s.crossDomain == null ) {

In this case, both undefined and null will be equal, which is a case where == is often used in preference to the strict equivalent:

if ( s.crossDomain === null || s.crossDomain === undefined ) {


One place where the difference between equality and strict equality becomes apparent is in JavaScript unit tests. Most assertion libraries include a way to check ‘shallow’ equality and ‘deep equality’. In CommonJS Unit Testing, these are known as assert.equal and assert.deepEqual.

In the case of deepEqual, there’s specific handling for dates and arrays:

equivalence is determined by having the same number of owned properties (as verified with Object.prototype.hasOwnProperty.call), the same set of keys (although not necessarily the same order), equivalent values for every corresponding key, and an identical “prototype” property


To understand how equality and strict equality work in JavaScript, primitive values and JavaScript’s implicit type conversion behaviour must be understood. In general, experienced developers advocate using ===, and this is good practice for beginners.

In recognising the confusion surrounding these operators, there is a significant amount of documentation on the topic. For example, Comparison Operators in Mozilla’s JavaScript Reference.

Minecraft Character WebGL, OpenSceneGraph, BroadStreet, Bootstrap

24 Aug 2012 | By Alex Young | Comments | Tags webgl threejs bootstrap backbone.js

Minecraft Character in WebGL

Minecraft Items demo

In Minecraft Character in WebGL, Jerome Etienne demonstrates how to render and animate Minecraft characters using his tQuery library. This was inspired by the Minecraft Items Chrome Experiment.


Mickey point cloud

OpenSceneGraph (GitHub: cedricpinson / osgjs, License: LGPL) by Cedric Pinson is a WebGL framework based on OpenSceneGraph – a 3D API typically used in C++ OpenGL applications. This means it’s possible for developers experienced with OpenSceneGraph to bring their projects across to a familiar environment that runs in modern browsers thanks to WebGL.


BroadStreet (GitHub: DarrenHurst / BroadStreet, License: MIT) by Darren Hurst is a set of controls for Backbone.js. It includes a list selector, iOS-style toggles and alerts, SVG icons, and labels.

Each control inherits from Backbone.View.extend, so the API looks like a standard Backbone object:

var toggle = new Toggle('controls', this).render();
toggle.setTitle('Example title');

The author recommends testing the project with a web server to avoid security restrictions caused when running the examples locally.

Bootstrap 2.1.0

Bootstrap 2.1.0 is out:

New docs, affix plugin, submenus on dropdowns, block buttons, image styles, fluid grid offsets, new navbar, increased font-size and line-height, 120+ closed bugs, and more. Go get it.

The Bootstrap homepage showcases the new features and has a slight redesign. Hopefully it’ll inspire Bootstrap users to customise their projects a little bit instead of using the same black gradient navigation bar on every single project!

How Ender Bundles Libraries for the Browser

23 Aug 2012 | By Rod Vagg | Comments | Tags ender frameworks modules libraries tutorials
This is a contributed post by Rod Vagg. This work is licensed under a Creative Commons Attribution 3.0 Unported License.

I was asked an interesting Ender question on IRC (#enderjs on Freenode) and as I was answering it, it occurred to me that the subject would be an ideal way to explain how Ender’s multi-library bundling works. So here is that explanation!

The original question went something like this:

When a browser first visits my page, they only get served Bonzo (a DOM manipulation library) as a stand-alone library, but on returning visits they are also served Qwery (a selector engine), Bean (an event manager) and a few other modules in an Ender build. Can I integrate Bonzo into the Ender build on the browser for repeat visitors?

What’s Ender?

Let’s step back a bit and start with some basics. The way I generally explain Ender to people is that it’s two different things:

  1. It’s a build tool, for bundling JavaScript libraries together into a single file. The resulting file constitutes a new “framework” based around the jQuery-style DOM element collection pattern: $('selector').method(). The constituent libraries provide the functionality for the methods and may also provide the selector engine functionality.
  2. It’s an ecosystem of JavaScript libraries. Ender promotes a small collection of libraries as a base, called The Jeesh, which together provide a large portion of the functionality normally required of a JavaScript framework, but there are many more libraries compatible with Ender that add extra functionality. Many of the libraries available for Ender are also usable outside of Ender as stand-alone libraries.

The Jeesh is made up of the following libraries, each of these also works as a stand-alone library:

  • domReady: detects when the DOM is ready for manipulation. Provides $.domReady(callback) and $.ready(callback) methods.
  • Qwery: a small and fast CSS3-compatible selector engine. Does the work of looking up DOM elements when you call $('selector') and also provides $(elements).find('selector'), $(elements).and(elements) and $(elements).is('selector').
  • Bonzo: a DOM manipulation library, providing some of the most commonly used methods, such as $(elements).css('property', 'value'), $(elements).empty(), $(elements).after(elements||html), and many more.
  • Bean: an event manager, provides jQuery-style $(elements).bind('event', callback) and others.

The Jeesh gives you the features of these four libraries bundled into a neat package for only 11.7 kB minified and gzipped.

The Basics: Bonzo

Bonzo is a great way to start getting your head around Ender because it’s so useful by itself. Let’s include it in a page and do some really simple DOM manipulation with it.

<html lang="en-us">
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>Example 1</title>
  <script src="bonzo.js"></script>
  <script id="scr">
    // the contents of *this* script,
    var scr = document.getElementById('scr').innerHTML

    // create a <pre></pre>
    var pre = bonzo.create('<pre>')

    // fill it with the script text, append it to body and style it
        fontWeight: 'bold',
        border: 'solid 1px red',
        margin: 10,
        padding: 10


You can run this as example1, also available in my GitHub repository for this article.

This should look relatively familiar to a jQuery user – you can see that Bonzo is providing some of the important utilities you need for modifying the DOM.

Bonzo Inside Ender

Let’s see what happens when we use a simple Ender build that includes Bonzo. We’ll also include Qwery so we can skip the document.getElementById() noise, and we’ll also use Bean to demonstrate how neatly the libraries can mesh together.

This is done on the command line with: ender build qwery bean bonzo. A file named ender.js will be created that can be loaded on a suitable HTML page.

Our script becomes:

    fontWeight: 'bold',
    border: 'solid 1px red',
    margin: 10,
    padding: 10
  .bind('click', function () {
    alert('Clickety clack');

You can run this as example2, also available in my GitHub repository for this article.

Bonzo performs most of the work here but it’s bundled up nicely into the $ object (also available as ender). The previous example can be summarised as follows:

  • bonzo.create() is now working when HTML is passed to $().
  • Qwery does the work when $() is called with anything else, in this case $('#scr') is used as a selector for the script element.
  • We’re using the no-argument variant of bonzo.text() to fetch the innerHTML of the script element.
  • Bean makes a showing with the .bind() call, but the important point is that it’s integrated into our call-chain even though it’s a separate library. This is where Ender’s bundling magic shines.
  • bonzo.appendTo() takes the selector argument which is in turn passed to Qwery to fetch the selected element from the DOM (document.body).

Also important here, which we haven’t demonstrated, is we can do all of this on multiple elements in the same collection. The first line could be changed to $('<pre></pre><pre></pre>') and we’d end up with two blocks, both responding to the click event.

Removing Bonzo

It’s possible to pull Bonzo out of the Ender build and manually stitch it back together again. Just like we used to do with our toys when we were children! (Or was that just me?)

First, our Ender build is now created with: ender build qwery bean (or we could run ender remove bonzo to remove Bonzo from the previous example’s ender.js file). The new ender.js file will contain the selector engine goodness from Qwery, and event management from Bean, but not much else.

Bonzo can be loaded separately, but we’ll need some special glue to do this. In Ender parlance, this glue is called an Ender Bridge.

The Ender Bridge

Ender follows the basic CommonJS Module pattern – it sets up a simple module registry and gives each module a module.exports object and a require() method that can be used to fetch any other modules in the build. It also uses a provide('name', module.exports) method to insert exports into the registry with the name of your module. The exact details here aren’t important and I’ll cover how you can build your own Ender module in a later article, for now we just need a basic understanding of the module registry system.

Using our Qwery, Bean and Bonzo build, the file looks something like this:

| Ender initialisation & module registry |
| (we call this the 'client library')    |
| 'module.exports' setup                 |
| Qwery source                           |
| provide('qwery', module.exports)       |
| Qwery bridge                           |
| 'module.exports' setup                 |
| Bean source                            |
| provide('bean', module.exports)        |
| Bean bridge                            |
| 'module.exports' setup                 |
| Bonzo source                           |
| provide('bonzo', module.exports)       |
| Bonzo bridge                           |

To be a useful Ender library, the code should be able to adhere to the CommonJS Module pattern if a module.exports or exports object exists. Many libraries already do this so they can operate both in the browser and in a CommonJS environment such as Node. Consider Underscore.js for example, it detects the existence of exports and inserts itself onto that object if it exists, otherwise it inserts itself into the global (i.e. window) object. This is how Ender compatible libraries that can also be used as stand-alone libraries work too.

So, skipping over the complexities here, our libraries are registered within Ender and then we encounter the Bridge. Technically the bridge is just an arbitrary piece of code that Ender-compatible libraries are allowed to provide the Ender CLI tool; it could be anything. The intention, though, is to use it as a glue to bind the library into the core ender / $ object. A bridge isn’t necessary and can be omitted – in this case everything found on module.exports is automatically bound to the ender / $ object. Underscore.js doesn’t need a bridge because it conforms to the standard CommonJS pattern and its methods are utilities that logically belong on $ – for example, $.each(list, callback). If a module needs to operate on $('selector') collections then it needs a special binding for its methods. Many modules also require quite complex bindings to make them work nicely inside the Ender environment.

Bonzo has one of the most complex bridges that you’ll find in the Endersphere, so we won’t be looking into it here. If you’re interested in digging deeper, a simpler bridge with some interesting features can be found in Morpheus, an animation framework for Ender. Morpheus adds a $.tween() method and also an $('selector').animate() and some additional helper methods.

The simplest form of Ender bridge is one that lifts the module.exports methods to a new namespace. Consider Moment.js, the popular date and time library. When used in a CommonJS environment it adds all of its methods to module.exports. Without a bridge, when added to an Ender build you’d end up with $.utc(), $.unix(), $.add(), $.subtract() and other methods that don’t have very meaningful names outside of Moment.js. They are also likely to conflict with other libraries that you may want to add to your Ender build. The logical solution is to lift them up to $.moment.utc() etc., then you also get to use the exported main function as $.moment(Date|String|Number). To achieve this, Moment.js’ bridge looks like this:

$.ender({ moment: require('moment') })

The $.ender() method is the way that a bridge can add methods to the global ender / $ object, it takes an optional boolean argument to indicate whether the methods can operate on DOM element collections, i.e. $('selector').method().

Bonzo in Parts

Back to what we were originally trying to achieve: we’re loading Bonzo as a stand-alone library and we want to integrate it into an Ender build in the browser. There are two important things we need to do to achieve this: (1) load Bonzo’s bridge so it can wire Bonzo into Ender, and (2) make Ender aware of Bonzo so a require('bonzo') will do the right thing because this is how the bridge fetches Bonzo.

Let’s first do this the easy way. With an Ender build that just contains Qwery and Bean and Bonzo’s bridge in a separate file named bonzo-ender-bridge.js, we can do the following:

<!-- the order of the first two doesn't matter -->
<script src="ender.js"></script>
<script src="bonzo.js"></script>
  provide('bonzo', bonzo)
<script src="bonzo-ender-bridge.js"></script>

If you look at the diagram of the Ender file structure above you’ll see that we’re replicating it with our <script> tags but replacing provide('bonzo', module.exports) with provide('bonzo', bonzo) as Bonzo has detected that it’s not operating inside of a CommonJS environment with module.exports available. Instead, it’s attached itself to the global (window) object. Both provide() and require() are available on the global object and can be used outside of Ender (for example, to extract Bean out of an integrated build you could simply var bean = require('bean').)

We can now continue to use exactly the same script as in our fully integrated Ender build example:

    fontWeight: 'bold',
    border: 'solid 1px red',
    margin: 10,
    padding: 10
  .bind('click', function () {
    alert('Clickety clack');

You can run this as example3, also available in my GitHub repository for this article.

Reducing <script> Tags

The main problem with the last example is that we have three <script> tags in our page with files loading (synchronously) from our server. We can trim that down to just two, and if bonzo.js is already cached in the browser then it’ll just be loading one script.

We could achieve this by hacking our ender.js file to include the needed code, or, we could create our own Ender package that contains our code so they will persist even after the Ender CLI tool has touched the file.

First we make a new directory to contain our package. We’ll include the Bonzo bridge as a separate file and also create a file for our provide() statement. Finally, a basic package.json file points to our provide() file as the source (“main”) of the package and the Bonzo bridge as our bridge (“ender”) file:

  "name": "fake-bonzo",
  "version": "0.0.0",
  "description": "Fake Bonzo",
  "main": "main.js",
  "ender": "bonzo-ender-bridge.js"

We then point the Ender CLI to this directory: ender build qwery bean ./fake-bonzo/ (or we could run ender add ./fake-bonzo/ to add it to the ender.js created in the above example).

The completed page now looks like this:

<html lang="en-us">
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>Example 4</title>
  <script src="bonzo.js"></script>
  <script src="ender.js"></script>
  <script id="scr">
        fontWeight: 'bold',
        border: 'solid 1px red',
        margin: 10,
        padding: 10
      .bind('click', function () {
        alert('Clickety clack');


You can dig further into this and run it as example4, also available in my GitHub repository for this article.


Hopefully this has helped demystify the way that Ender packages libraries together; it’s really not magic. If you want to dig deeper then a good place to start would be to examine the client library that appears at the top of each Ender build—it’s relatively straightforward and fairly short.

Node Roundup: 0.8.7, Buffet, HARedis, Deployd

22 Aug 2012 | By Alex Young | Comments | Tags node modules frameworks WebSocket redis libraries
You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.8.7

Node 0.8.7 is out, which includes fixes for SSL, TLS, buffer and crypto issues, and also a few Windows-specific problems. I noticed someone posted about an issue with the latest npm in Windows, but other than that 0.8.7 seems solid.


Buffet (License: MIT, npm: buffet) by Carlos Rodriguez is a “performance-oriented” static file server:

Buffet takes a fully-bufferred approach – all files are fully loaded into memory when your app boots, so you will never feel the burn of the filesystem. In practice, this is immensely efficient. So much so that putting Varnish in front of your app might even make it slower!

It supports gzip, and will update files when they’re changed. The name of the index.html and 404.html files can be changed, and other configuration options include maxAge for setting the Cache-Control header.

The author has included Mocha tests and the project is on Travis CI.


HARedis (License: MIT, npm: haredis) also by Carlos Rodriguez is a wrapper around node_redis that helps build fault-tolerant clusters of Redis servers. The main API difference is createClient, which accepts an array of hosts and ports, and this works with colon-separated strings for 'ip:port'.

Carlos has included the test suite from the original redis module, so running make test-cluster or make test can be used to test the project.


Deployd (GitHub: deployd / deployd, License: Apache 2.0, npm: deployd) by Ritchie Martori and the Deployd team is a toolkit for building real-time APIs suited to web and mobile applications.

Deployd applications are created with a command-line tool called dpd. A newly created app includes a web IDE for managing the applications resources – this is basically a schema that Deployd will use to generate a suitable RESTful API. There’s a Deployd Hello World tutorial that covers the basics, and a Deployd screencast.

The project is built on technologies like Socket.IO and MongoDB, and includes tests written with Mocha.

jQuery Roundup: Infinity.js, lorem, oriDomi

21 Aug 2012 | By Alex Young | Comments | Tags jquery plugins
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.



Infinity.js (GitHub: airbnb / infinity, License: BSD) from developers at Airbnb is an infinite scrolling plugin based on the iOS UITableView class. It’s implemented by using containers that move content in and out of the DOM based on throttled scroll events, to keep scrolling smooth. The current version has some caveats – ListViews can’t be nested or have a height set by CSS.

To back up the performance claims, the authors have made demo pages with Infinity.js turned on and turned off. At least in my browser, it’s clear that Infinity.js improves the performance. Also, several performance enhancements are currently planned, including changing the internal ListItem array to use a self-balancing binary tree.


lorem (License: MIT, npm: lorem) by Stanley Shyiko is a text generator that works with Node and browsers, and it includes optional jQuery plugin support:


The author has included Nodeunit tests, and a build script.


oriDomi (GitHub: dmotz / oriDomi, License: MIT) by Dan Motzenbecker is a small script with optional jQuery support that creates an effect on images and web fonts that looks like folding paper, by using CSS 3D transforms.

  vPanels: 3
, hPanels: 10
, perspective: 200
, speed: 500
, shading: false

It works best when it can figure out the dimensions of the element it’s applied to, so it’s probably a good idea to ensure images used with the effect have width and height attributes.

JS101: The Language Past and Present

20 Aug 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

We’ve covered a lot of ground since the first JS101, but the truth is I’ve missed out an important question: what is JavaScript, and who controls it?

I’ve answered this question and covered a lot more in the History of JavaScript series. This post is a brief introduction, and after reading this post you should know the basics of JavaScript and its relationship to ECMAScript.

Who Made JavaScript?

JavaScript was created by Brendan Eich in 1995 for Netscape. Netscape submitted JavaScript to Ecma International, which is a standards organization based in Geneva. The standardised version is known as ECMAScript.

What is ECMAScript?

Most articles on sites like DailyJS will refer to ECMA-262, ECMAScript 3, and ECMAScript 5. We usually abbreviate these terms to ES3 and ES5.

  • ECMA-262 is the name of the specification, of which there are five editions
  • ECMAScript 3 (or ECMA-262, edition 3) was published in December 1999, and was supported by Netscape 6 and IE 5.5
  • ECMAScript 5 (or ECMA-262, edition 5) was published in December 2009 and is supported by Firefox 4+, Safari 6: ES5 compatibility table

ECMAScript 5 adds a lot of features that we’ve already started to take for granted: including new array methods like forEach, new Object methods like Object.create, property attributes, function binding, and more.

The Future

ECMAScript is still being actively developed. It’s tentatively known as ES.next (ECMA-262 Edition 6), and ES.next working drafts can be downloaded from the ECMAScript wiki.

Proposals for the language are collected on the strawman wiki, and discussed in detail by several contributors on the wiki and mailing lists. To keep up with this, I often check the wiki’s recent changes and the es-discuss mailing list.

Brendan Eich’s blog covers a lot of the major developments as well. For example, his latest post mentions ES6 and the relationship between the standards makers and the enthusiastic JavaScript developer community.

The language will change, and as new standards are made available you’ll need to know what your given platform or browser supports.

App.net Node Module, Prototype 1.7.1, Self, Qwerty Hancock, MilkChart

17 Aug 2012 | By Alex Young | Comments | Tags libraries node browser audio social prototype graphs

App.net Node Module

There’s already an App.net Node module: damienklinnert / appdotnet (License: MIT, npm: appdotnet. Created by Damien Klinnert, it uses the popular request HTTP module, and has Mocha tests. It supports authentication, users, and posts.

Creating a post is very simple:

client.createPost(config.post_data, function(err, post) {
  // Do something with `post`

Prototype 1.7.1

(SFX: Simple Minds - Alive And Kicking)

Prototype 1.7.1 has been released, which includes a rewrite of the DOM code, ECMAScript 5 compatibility, as well as other bug fixes.

Many of you have wondered whether Prototype is “dead,” and I can say that it definitely isn’t. But because of the way I work on Prototype - months of inaction followed by a flurry of commits and bug fixes - it’s fair to say that Prototype hibernates for long periods of time.


Self (License: MIT, npm: self) by Ryan Munro is a class library based on Python. It supports inheritance, mixins, static properties, and can work with plain old prototype classes and Backbone.

Self is class-based sugar that’s perfect for continuation-passing style. No more var that = this;! The implicit this variable is changed to an explicit self variable that your inner functions inherit. Self plays nicely with existing prototypal, and Backbone OOP.

Self can be used with browsers and in Node programs, and includes tests for both environments.

Qwerty Hancock

Query Hancock

Qwerty Hancock (GitHub: stuartmemo / qwerty-hancock, License: MIT) by Stuart Memo is a “vector qwerty keyboard”. The project’s site demonstrates the keyboard by hooking it up to some Audio API code, so it’s actually a reusable keyboard widget that could be used to build other music-related projects.


MilkChart (License: MIT) by Brett Dixon is a graph library for MooTools. It generates graphs that look like Excel. It’s designed to transform HTML tables into charts, so it’s easy to integrate it with existing markup that requires graphs.

Backbone.js: Internals Summary

16 Aug 2012 | By Alex Young | Comments | Tags mvc tutorials backbone.js code-review

Over the last month we’ve looked at Backbone’s internals in detail. This post summarises these findings.

To recap, here’s a list of all the parts in Backbone.js: Hacker’s Guide:

  • Part 1: Setup, Events, Models
  • Part 2: Constructor, Inheritance, Collections, Chainable API
  • Part 3: Router, History, Views
  • Part 4: Inheritance, Sync

Leverage Events

Backbone’s classes are designed to be inherited from. Every single one of these classes inherits from Backbone.Events:

  • Backbone.Model
  • Backbone.Collection
  • Backbone.Router
  • Backbone.History
  • Backbone.View

That means when designing applications built with Backbone, events are a key architectural component. Events are the standard way to deal with user interface actions, through the declarative event bindings on views, and also model and collection changes. However, you can easily add your own custom events.

When learning Backbone it’s important to get a feel for the built-in event names. Incorrectly binding a collection reset event, for example, could cause your application to render more often than it should. Mastering events is one of the quickest ways to become more productive with Backbone.


Since Backbone depends on Underscore, it’s worth keeping this in mind when dealing with any kind of arrays or collections of data. Also, familiarity with Underscore’s methods will help work with Backbone.Collection effectively.


It’s easy to slip into using $, but avoid this where possible. Backbone caches a view’s element, so use this.$el instead. Design views based on the single responsibility principle.

It might be tempting to let “container” view render HTML directly by using $().html, but resisting the temptation and creating a hierarchy of views will make it much easier to debug your code and write automated tests.

Interestingly, Backbone doesn’t have a lot of code dedicated to templates, but it can work with the template method. I use this with RequireJS text file dependencies to load remote templates during development, then I use the RequireJS build script to generate something suitable for deployment. This makes code easy to test and fast to load.

API Style

Backbone’s API is thankfully very consistent. Even the history API accepts a silent option, which is used throughout the library to stop events from firing when they’re not required.

Backbone’s collections have Underscore’s chainable API, which can be handy, but care must be taken to use this correctly.

Testing Backbone

So far I’ve been reviewing Backbone’s code to demystify the framework as a whole. However, it’s worth noting that other technologies work very well with Backbone and Underscore. RequireJS and AMD modules can be a great way to break up projects.

However, one area that Backbone doesn’t address is testing. This is unfortunate, because testing Backbone projects definitely isn’t obvious. In Unit Testing Backbone.js Apps With QUnit And SinonJS, Addy Osmani describes one method in detail.

I have the following rules for testing Backbone projects:

  1. The full application should be running during testing
  2. Tests shouldn’t depend on any markup in the test harness HTML file (or as little as possible)
  3. Tests shouldn’t touch the network for data

The second rule in particular is aided by using templates loaded by RequireJS and avoiding those pesky calls to $() in views.

Node Roundup: Surviving npm Downtime, Waf Wall of Shame, stream-chat, Vein

15 Aug 2012 | By Alex Young | Comments | Tags node modules RPC WebSocket npm templating
You can send in your Node projects for review through our contact form or @dailyjs.

Surviving npm Downtime

On Sunday morning (UTC) part of npm’s service stopped functioning correctly, which meant the command-line tool failed to download packages. In response to this, Dominique Sandoz stepped up and created a mirror. Mirrors can be used by changing the location of the npm registry:

npm set registry http://npm.example.com
npm set registry https://registry.npmjs.org

Fortunately npm is now working correctly, but to help prepare for future downtime I recommend bookmarking this gist that Dominique wrote containing a list of npm mirrors and proxies.

During the downtime, several other users also offered their own solutions, mostly collaborating on Twitter and IRC. For example, Maciej MaƂecki created a proxy-based solution.

To my knowledge there has been no official statement on the service outage, and additionally there is no official Node/npm service status page. Hopefully someone will write up details about the outage on blog.nodejs.org, and outline the preventative measures taken to ensure future stability.

Node-waf Wall of Shame

Isaac Schlueter posted a Tweet referencing what he calls the “Node-waf wall of shame”:

Node-waf wall of shame: http://j.mp/node-waf-users Upgrade your packages to node-gyp. http://npm.im/node-gyp #deathtowaf

As I mentioned in the Windows and Node series, it’s time to move addons over to node-gyp.


stream-chat (License: MIT) by Raynos is a chat app based around streams. It uses the boot and multi-channel-mdm modules by the same author to route streams between browsers and Node servers.

An added bonus is the author has designed the chat app to be scalable by using seaport and mountie by James Halliday. Seaport helps manage clusters of servers, while mountie allows applications to be composed of smaller servers behind mount points. Routing is handled by bouncy. These modules help design larger systems according to the concept of separation of concerns, which suits Node web applications.


MinnaHTML.js (License: GPL v3, npm: minnahtml) by Robee Shepherd is an async-friendly HTML object library that can be used to build HTML:

var mh = require('minnahtml').mh
  , html = new mh.Html()
  , head = new mh.Head(html)

 new mh.Title(head).data.content = 'Example';

// <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
// <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
//  <head>
//   <title>
//    Example
//   </title>
//  </head>
// </html>

The author has provided a walkthrough that covers more features in the project’s readme file.


Vein (License: MIT, npm: vein) is a WebSocket RPC module. It includes both client and server code, and a minimised build for browsers. RPC methods can be added using vein.add, and then called from clients:

// Server
vein.add('multiply', function(res, numOne, numTwo) {
  res.reply(numOne * numTwo);

// Browser
var vein = Vein.createClient();
vein.on('ready', function(services) {
  vein.multiply(2, 5, function(num) {
    // num === 10

jQuery Roundup: jQuery 1.8, BBSearch, MDMagick, Document-Bootstrap, DownloadBuilder.js

14 Aug 2012 | By Alex Young | Comments | Tags jquery plugins backbone.js sessionStorage files
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery 1.8

jQuery 1.8 has been released. jQuery 1.8 makes some fairly significant changes:

  • The selector engine has been rewritten
  • Animations have been reworked
  • .css and .animate will automatically add vendor prefixes
  • The size has been reduced compared to jQuery 1.7.2
  • Grunt build system


BBSearch (GitHub: fguillen / BBSearch, License: CC BY 3.0) by Fernando Guillen is a find-as-you-type style plugin that’s designed to work with Backbone.js. It can also work with JSONP APIs, and the author has included demos that use GitHub and Twitter.

  url: 'https://api.github.com/legacy/repos/search/#bbsearch-query#?callback=?&'
, itemTemplate: '<p>[@<%= owner %>] <a href="<%= url %>"><%= name %></a></p>'
, resultsElement: $('#results-1')
, parse: function(response) { return response.data.repositories; }



MDMagick (GitHub: fguillen / MDMagick, License: CC BY 3.0) also by Fernando Guillen is a Markdown interface for jQuery. It uses Showdown, which is a Markdown parser for JavaScript, and a-tools for handling text selections.

Document-Bootstrap and DownloadBuilder.js

Document-Bootstrap (GitHub: gfranko / Document-Bootstrap, License: MIT) by Greg Franko is a boilerplate for creating responsive Bootstrap projects. It also includes DownloadBuilder.js (GitHub: gfranko / DownloadBuilder.js, License: MIT), a project by the same author that uses the HTML5 File API to create optimised client-side scripts.

DownloadBuilder.js supports concatenating local files and files hosted on GitHub. It can also cache Ajax/JSONP requests by using sessionStorage.

DailyJS is Looking for Writers

13 Aug 2012 | By Alex Young | Comments | Tags community news

Over the last three years I’ve written over 700 articles for DailyJS. I’ve written through national holidays, trips to Europe and Asia, and I’ve enjoyed every minute of it! The time has come, however, to look for more writers. In September I’m going to become a father, and naturally family obligations will take priority for a few weeks.

Rather than leave readers without their daily dose of JavaScript news and tutorials, I’m looking for writers to contribute to the site. If you’re an open source developer and would like to promote your latest Node module or client-side library by writing a tutorial: this is your chance! I’m also interested in hearing from developers of commercial services that are relevant to JavaScript developers.

Before writing anything, fill out this form to get in touch. I’ll let you know if your suggestion is appropriate for the site.

Writing Guide

  • Articles do not need to be long – three to five paragraphs is great, otherwise consider writing a series of articles
  • Markdown is fine, although we use weird tags for code samples – here is an example post
  • British or American English is acceptable
  • DailyJS reserves the right to edit your article before publishing it


Articles will be paid for at a base rate of $25. Payment terms are negotiable, and may be subject to exchange rate conversion.

Submit your article idea here.

HubSearch, canvas-charts, Motown

10 Aug 2012 | By Alex Young | Comments | Tags libraries browser ui windows apps metro



HubSearch (GitHub: jgallen23 / hubsearch) by Greg Allen is a GitHub search interface built with Bootstrap, Underscore, and his own Fidel library for Backbone-style controllers.

I spend a lot of time searching GitHub to find projects to write about, so it’s good to see a tool that tries to improve on GitHub’s inadequate search interface.


canvas-charts (License: MIT) by Praneet Loke is a graph library that only relies on the HTML5 Canvas API. The library includes a method to check if the Canvas element is supported, and it accepts an object containing options:

var chartingCanvas = new CanvasCharts();
if (chartingCanvas.isCanvasSupported()) {
    gradientColor1: '#cd9603'
  , gradientColor2: '#f1de3f' // etc.

  chartingCanvas.createCanvas($('graph'), width, height);
  // Given suitable arrays of labels for the x and y axes
  chartingCanvas.drawChart(xaxis, 90, yaxis, 35, [10, 20, 30 20, 10]);


Motown (GitHub: mtilchen / motown, License: LGPL v3) by Matthew P. Tilchen is a library for creating Metro-style Windows 8 applications using HTML, CSS, and JavaScript. Matthew sent this in before Microsoft decided to change the Metro name, but at this point everyone interested in this project should understand the name’s origin.

The WinJS libraries and bindings to WinRT provide a solid foundation for building applications but I feel that a significant gap remains. Microsoft […] intentionally left […] this for the development community to fill. I created the Motown JavaScript library […] to fill the gap.

This library is based on Microsoft’s JavaScript Windows API, and is built according to Microsoft’s recommendations:

Microsoft recommends that developers use a “single-page” style of navigation instead of a “multi-page” style in their applications.

Motown also supports navigation transition animations, application life cycle methods, and a declarative approach to binding HTML views to JavaScript. The project includes a Visual Studio 2012 plugin for creating new Motown apps.

Backbone.js: Hacker's Guide Part 4

09 Aug 2012 | By Alex Young | Comments | Tags mvc tutorials backbone.js code-review

Last week we looked at Backbone’s History and View APIs. We’re coming to the end of this detailed look at Backbone’s internals, but there are still a few interesting things left:

  • Backbone’s inheritance implementation
  • Backbone.sync

Backbone’s inheritance Implementation

The comments indicate that the inherits function is inspired by goog.inherits. Google’s implementation is from the Closure Library, but Backbone’s API accepts two objects (incorrectly referred to as a hash) containing “instance” and “static” methods. Each of Backbone’s objects has an extend method:

Model.extend = Collection.extend = Router.extend = View.extend = extend;

Most development with Backbone is based around inheriting from these objects, and they’re designed to mimic a classical object-oriented implementation.

Backbone uses Underscore’s extend method:

each(slice.call(arguments, 1), function(source) {
  for (var prop in source) {
    obj[prop] = source[prop];
return obj;

This isn’t the same as ES5’s Object.create, it’s actually copying properties (methods and values) from one object to another. Since this isn’t enough to support Backbone’s inheritance and class model, the following steps are performed:

  1. The instance methods are checked to see if there’s a constructor property. If so, the class’s constructor is used, otherwise the parent’s constructor is used (i.e., Backbone.Model)
  2. Underscore’s extend method is called to add the parent class’s methods to the new child class
  3. The prototype property of a blank constructor function is assigned with the parent’s prototype, and a new instance of this is set to the child’s prototype property
  4. Underscore’s extend method is called twice to add the static and instance methods to the child class
  5. The child’s prototype’s constructor and a __super__ property are assigned

This pattern is also used for classes in CoffeeScript, so Backbone classes are compatible with CoffeeScript classes.

Update: Jeremy Ashkenas clarified this process on Twitter:

… it’s just your basic prototype chain, plus one extra goodie: any constructor properties (static) are copied over as well.

Backbone’s Sync API

The Backbone.sync method is intended to be overridden to support other backends. The built-in method is tailed to a certain breed of RESTful JSON APIs – Backbone was originally extracted from a Ruby on Rails application, which uses HTTP methods like PUT the same way.

The way this works is the model and collection classes have a sync method that calls Backbone.sync. Both will call this.sync internally when fetching, saving, or deleting items.

The sync method is called with three parameters:

  • method: One of create, update, delete, read
  • model: The Backbone model object
  • options: May include success and error methods

Implementing a new sync method can use the following pattern:

Backbone.sync = function(method, model, options) {
  var requestContent = {}, success, error;

  function success(result) {
    // Handle results from MyAPI
    if (options.success) {

  function error(result) {
    // Handle results from MyAPI
    if (options.error) {

  options || (options = {});

  switch (method) {
    case 'create':
      requestContent['resource'] = model.toJSON();
      return MyAPI.create(model, success, error);

    case 'update':
      requestContent['resource'] = model.toJSON();
      return MyAPI.update(model, success, error);

    case 'delete':
      return MyAPI.destroy(model, success, error);

    case 'read':
      if (model.attributes[model.idAttribute]) {
        return MyAPI.find(model, success, error);
      } else {
        return MyAPI.findAll(model, success, error);

This pattern delegates API calls to a new object, which could be a Backbone-style class that supports events. This can be safely tested separately, and potentially used with libraries other than Backbone.

There are quite a few sync implementations out there:

Node Roundup: Node 0.8.6, Axon, NextFlow

08 Aug 2012 | By Alex Young | Comments | Tags node modules async pubsub
You can send in your Node projects for review through our contact form or @dailyjs.

Node 0.8.6

Node 0.8.6 is out, and this release is the first to include binary distributions for all supported Unix systems.

The 0.6 series has also been updated, with the release of 0.6.21. This release fixes a bug in fs.watch that affected Solaris.


Axon (License: MIT, npm: axon) by TJ Holowaychuk is a zeromq-inspired message-oriented socket library. It uses the push/pull and publish/subscribe patterns, and features a lightweight wire protocol that supports binary messages.

Axon is JavaScript, so it might work well in situations where a messaging system is desired but additional software installation is not. The API is friendly for Node developers, particularly the EmitterSocket object which behaves like Node’s EventEmitter.

TJ has included information on the protocol and some rough benchmarks.


NextFlow (License: MIT, npm: nextflow) by JP Richardson is a control flow library for Node that has a CoffeeScript-friendly API. Rather than using a chainable API or a list of arguments, NextFlow accepts an object:

next = require('nextflow')

vals = []
x = 0

next flow =
  1: ->
  2: ->
    x = Math.random()
  3: (num) ->
  4: ->
  5: ->
    console.log vals[0] #is 1
    console.log vals[1] #is 2
    console.log vals[2] #is x
    console.log vals[3] #is 4

The author has included CoffeeScript comparisons with well-known Node control flow libraries.

jQuery Roundup: AutobahnJS, Grid Builder, Best Ampersand

07 Aug 2012 | By Alex Young | Comments | Tags jquery plugins libraries WebSocket ui
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.


AutobahnJS (GitHub: tavendo / AutobahnJS, License: MIT) from Tavendo GmbH is a client library that implements the The WebSocket Application Messaging Protocol (WAMP). The API is asynchronous and promise-based, so it can use jQuery’s Deferred object or similar implementations. Publish/Subscribe and RPC are both supported by the library.

The RPC API looks like this:

// WAMP server
var wsuri = 'ws://localhost:9000';
  // WAMP session was established
  function(session) {
    // Asynchronous RPC, returns promise object
    session.call('http://example.com/simple/calc#add', 23, 7).then(
      // RPC success callback
      function(res) {
        console.log('got result:', res);

      // RPC error callback
      function(error, desc) {
        console.log('error:', desc);

  // WAMP session is gone
  function(code, reason) {

The authors have written tutorials for Publish/Subscribe with AutobahnJS and RPC.

jQuerin Grid Builder

jQuerin Grid Builder (GitHub: kanakiyajay / jQuerin-grid-builder, License: MIT/GPL) by Jay Kanakiya is an interactive tool that generates HTML and CSS for grid-based layouts.

Attributes like class and id can be added to cells, and multiple levels of rows and columns can be created once you get the hang of the interface.

Best Ampersand

Best Ampersand (GitHub: gmurphey / jQuery.Best-Ampersand, License: MIT/GPL) by Garrett Murphey is a simple plugin that wraps ampersands in spans so they can be styled with the best available ampersand. Garrett has written this plugin using a TDD approach, and he’s included unit tests and the build script.

He also sent in Outbound Analytics, which can help track outbound links with Google Analytics.

JS101: Enumeration

06 Aug 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

In this article we’ll look at JavaScript’s enumeration capabilities. This is partly related to scope, so take a look at JS101: A Brief Lesson on Scope if you haven’t read it yet.

Correctly Using for-in

The for-in statement is intended to be used to enumerate over the properties of an object. Inherited properties are included, and to avoid iterating over them hasOwnProperty should be used.

This example demonstrates using for-in, and shows what happens when someone adds a property to a native prototype:

Object.prototype.bad = undefined;

var name, names;

names = {
  bill: { age: 44 }
, bob: { age: 22 }
, john: { age: 29 }

for (var name in names) {
  if (names.hasOwnProperty(name)) {
    console.log(name, names[name].age);
  } else {
    console.log('Inherited:', name);

The output will show the inherited property that we don’t want. Even though the property has been set to undefined, it still exists and will be present when enumerated over. Some libraries may add properties this way (even though it’s generally considered bad practice), so it’s wise to use the following pattern:

for (var prop in exampleObject) {
  if (exampleObject.hasOwnProperty(prop)) {
    // Do stuff

The Underscore.js library uses the same pattern in its implementation of _.each:

for (var key in obj) {
  if (_.has(obj, key)) {
    if (iterator.call(context, obj[key], key, obj) === breaker) return;

Correctly Extending Objects

In ECMAScript 5, properties have an enumerable attribute. If this is set to fault, then the property won’t be included in a loop with for-in. There’s also a method called Object.prototype.propertyIsEnumerable, and methods like Object.keys will respect it.

If I really wanted to add a property to Object, then I could take advantage of this to correctly extend the built-in object:

Object.defineProperty(Object.prototype, 'bad', {
   value: undefined
 , enumerable: false // This property is not enumerable

var name, names;

names = {
  bill: { age: 44 }
, bob: { age: 22 }
, john: { age: 29 }

for (var name in names) {
  if (names.hasOwnProperty(name)) {
    console.log(name, names[name].age);
  } else {
    console.log('Inherited:', name);

Running this example will leave out the bad property.

Notice that this doesn’t just apply to adding properties to native objects – you should also take enumerable into account when adding properties to your own objects.

ECMAScript 5 Array.prototype Methods

ECMAScript 5 introduces some handy methods to Array.prototype:

  • forEach(callback): Run callback over each element
  • filter(callback): Returns a new array for each item where callback returns true
  • map(callback): Run callback over each element, store the result, then return a new array containing the results
  • some(callback): If callback returns true, then stop iterating and return true

There are more methods, including indexOf, lastIndexOf, reduce, and reduceRight. These methods also take a thisArg parameter, which changes the value of this in the callback.

Remember that these are all methods on Array. To use them with an object, one approach is to call Object.keys. The previous example could be rewritten like this:

var name, names;

names = {
  bill: { age: 44 }
, bob: { age: 22 }
, john: { age: 29 }

Object.keys(names).forEach(function(name) {


In JS101: A Brief Lesson on Scope, I provided an example that showed how creating methods inside loops can cause confusing scope issues. Since forEach uses a callback, we now have a new scope for each iteration:

function example() {
  var o = {};

  [0, 1, 2, 3].forEach(function(i) {
    o[i] = function() { console.log(i); };



This will correctly output 0 1 2 rather than the 3 3 3 that was printed with the for example.


If you’re working with an array of items, a simple for loop will still perform better than forEach:

var length = values.length, i;
for (i = 0; i < length; i++) {
  // Do something

There are dozens of benchmarks for this on jsPerf, but in general the good old fashioned for loop will beat forEach.

Relationship to Underscore.js

Underscore.js and jQuery both include methods that work like forEach. This makes it easier to write code that’ll work with older browsers.

Underscore works slightly different to forEach because it doesn’t extend Array.prototype, or any other built-in object. Instead, the array has to be passed as an argument:

_.forEach([0, 1, 2], function(i) {

The ECMAScript 5 forEach method will be used if it’s available, otherwise a for loop will be used instead.