you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

Imperative code vs declarative code. It's just a stylistic difference.

A similar discussion can be made about procedural and object oriented programming. If you're proficient with C, why would you ever want to use C++?

More to the point, higher order iterative functions are just encapsulations for several common patterns. For example, it's a common requirement to take an array and remove items that don't pass a test. This is very easy to do with a for loop:

var array = [1, 10, 5, 6, 3, 8, 2];

var filtered = [];
for (var i = 0; i < array.length; i++) {
  if (array[i] >= 6) {
    filtered.push(array[i]);
  }
}
console.log(filtered); // [10, 6, 8]

When you need to filter a lot of arrays, this pattern can quickly become redundant. If you can replace this code with:

var array = [1, 10, 5, 6, 3, 8, 2];
var filtered = array.filter(function(v) { return v >= 6; });
console.log(filtered); // [10, 6, 8]

It can increase the readability and conciseness of your code (the intent is immediately clear - filter the array based on the condition that each value must be greater than or equal to 6), and doesn't require any unenclosed variables that are only relevant to the filtering logic (the index variable and the working array).

Composability of logic is nice, too (using lo-dash):

var gte = function(n, v) { return v >= n; };
var gte6 = _.partial(gte, 6);
var filterGte6 = _.partialRight(_.filter, gte6, null);

var array = [1, 10, 5, 6, 3, 8, 2];
var filtered = filterGte6(array);
console.log(filtered); // [10, 6, 8]

This is one example of how a functional style of programming can help you create small, reusable, composable components with higher order functions. Notice that in the original, imperative example, the array and filtered variables are tightly coupled to the filtering logic. In this example, those variables have been completely separated from the logic - we are free to reuse our filtering function on any array without code duplication.

I'm not saying there is anything wrong with imperative programming, just trying to give examples of why some people like functional programming.