I'm back working on some JavaScript, just like the old times, adding client-side UI dynamics. In spite of still being hard to work and debug (at least in IE), it allows me to play with a different language. I realized the worst thing you can do with JavaScript is use it like Java, it works but you'll miss the interesting features like prototyping and higher order functions.
This week I found that Mozilla JavaScript implements useful iteration methods were you can pass functions to operate on the collection:
filter, forEach, every, map, and some:
filter
Selects the elements of the collection that satisfy the function
forEach
Applies a function to all the elements of the array
every
Returns true if every element of the array satisfies the function
some
Returns true if at least one element satisfies the function
map
Creates a new array with the results of calling a provided function on every element in this array.
As an example, you can easily write:
funtion doSomethig(element){ /*whatever*/}
and then:
aCollection.forEach(doSomething)
Suddenly, JavaScript coolness factor has increased for me :-)
Those functions are standard in Mozilla JavaScript, but they provide the source code, and is small enough to include it if you're using another browser. And as the objects are “open” and you create new ones by prototyping, you just need to add the code to the object you want (as long as is “array” like) it will work.