forEach goodness.
by Peter Higgins

This morning, I was again reminded about something I am continually forgetting and it’s worth documenting, so here goes:

Not only does dojo.forEach iterate over an array passing the element to a function each time:

var arr = ["one","two","three"];
// print one, two, three
dojo.forEach(arr,function(el){ console.log(el); });

It also passes the current index in the array (which I find uber helpful):

var arrOne = ["a","b","c"];
var arrTwo = ["one","two","three"];
     // better than idx++
     var alt = arrTwo[idx];

You can pass a named function, too. forEach automatically passes the element anyway:

var connects = [];
// later:

It also scopes, making “this” useful:

var foo = {
     myMethod: function(el){

And to top it alll off, dojo.query / dojo.NodeList has a .forEach method, which assumes scope, and otherwise
works the same (though the array is each domNode in the results:)

// add some text to all nodes class="links"
      n.innerHTML += " - touched ";

Hope this helps.


This entry was posted on Tuesday, February 19th, 2008 at 4:00 pm and is filed under Dojo Cookies. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “forEach goodness.”

  1. DojoCampus » Blog Archive » Demystifying Says:

    [...] process you can go through to make your code more “async”-friendly. First, rewrite using dojo’s uber-cool [...]

  2. Learning Dojo | SitePen Blog Says:

    [...] (article) forEach goodness [...]

Leave a Reply

You must be logged in to post a comment.