HTML and CSS Reference
In-Depth Information
First class functions are a powerful concept. As another example, consider this as a stand-
alone function assigned to a variable:
> f2 = function(i) {
return i % 2 == 0;
}
This function accepts a number, and returns true if the number is even, and false if it is odd:
> f2(9)
false
> f2(10)
true
Now, create an array of all the numbers between 1 and 10, and assign that to variable a :
a = [1,2,3,4,5,6,7,8,9,10]
As mentioned earlier, JavaScript arrays are objects, and therefore they contain methods.
One of the methods supported by arrays is filter . This method accepts a function as a para-
meter; the filter method will then pass each member of the array in turn to the function
provided, and at the end return a new array containing each value that evaluated to true in
that function. This means we can create a new array with all the even numbers as follows:
> a.filter(f2)
[2, 4, 6, 8, 10]
//
The filter , map and reduce methods referred to in these examples were only ad-
ded to JavaScript in ECMAScript version 5. As such they are not natively sup-
ported in older browsers, including IE8. They can however easily be added as
polyfills.
 
Search WWH ::




Custom Search