Here’s an example to convert the following imperative style of coding in JavaScript to functional style. The code prints out a list of even numbers in an array.
var imperativeStyle = function(){
var numbers = [1,2,3,4,5,6,7,8,9,10];
var evenNumbers = [];
for(var i=0;i<numbers.length;i++){
if(numbers[i] % 2 == 0)
evenNumbers.push(numbers[i]);
}
console.log(evenNumbers);
};
The functional approach can be implemented using the filter() method of the Array class in JavaScript like this.
var functionalStyle = function(){
var numbers = [1,2,3,4,5,6,7,8,9,10];
var evenNumbers = numbers.filter(function(num){
return num % 2 == 0});
console.log(evenNumbers);
};
functionalStyle();
The filter() function is a higher-order function that applies the function argument to all the elements in an array and returns a new collection.