views:

91

answers:

3

Hello,

I came across the following code fragment in a CouchDB book.

function(doc) {
  doc.tags && doc.tags.forEach(function(tag) {
    emit(tag, 1);
  });
}

Can some one explain how does the function(tag) part works?

Thanks and regards,

raj

+1  A: 

forEach simply iterates over array and calls function you pass to it with every element it finds.

Be aware that not every browser support it, there's helper function $.forEach in jQuery, it is safer in terms of browser support.

vava
+1  A: 
function(tag) {...}

gets called "for each" tag in "doc.tags" with the "tag" argument passed to the lambda function in question.

jldupont
+5  A: 

This is called an anonymous inline function expression. It creates a function and gives you a reference to it, similar to if you had written:

function emitTag(tag) {
    emit(tag, 1);
}
doc.tags && doc.tags.forEach(emitTag);

The array.forEach method calls the given function once for each of the items in array in order. It is a standard method in ECMAScript Fifth Edition and has been in many browsers for some time, but not JScript (IE). I am guessing couchdb takes care of that issue for you though.

bobince
Thanks every one for your nice answers and quick response :)
Rajkumar S
This is map function in CouchDB. That doesn't run in Browser. It runs on server in spidermonkey. So you can use any latest Javascript trick that spidermonkey supports
nexneo
Ah, that makes sense then. Spidermonkey has supported the Fifth Edition Array methods for ages.
bobince