Javascript – Meaning of forEach(function(tag) in JavaScript

couchdbjavascript

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

Best Answer

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.