Beginner JavaScript OOP vs Functional

inthenameofmusik

I'm just starting to research different programming styles (OOP, functional, procedural).

I'm learning JavaScript and starting into underscore.js and came along this small section in the docs. The docs say that underscore.js can be used in a Object-Oriented or Functional style and that both of these result in the same thing.

_.map([1, 2, 3], function(n){ return n * 2; });
_([1, 2, 3]).map(function(n){ return n * 2; });

I don't understand which one is functional and which one is OOP, and I don't understand why, even after some research into these programming paradigms.

Dan Prince

There's no correct definition for what is and isn't "functional", but generally functional languages have an emphasis on simplicity where data and functions are concerned.

Most functional programming languages don't have concepts of classes and methods belonging to objects. Functions operate on well-defined data structures, rather than belonging to the data structures.

The first style _.map is a function in the _ namespace. It's a standalone function and you could return it or pass it to another function as an argument.

function compose(f, g) {
  return function(data) {
    return f(g(data));
  }
}

const flatMap = compose(_.flatten, _.map);

It's not possible to do the same for the second style, because the method instance is intrinsically tied to the data used to construct the object. So I'd say that the first form is more functional.

In either case, the general functional programming style is that data should be the final argument to the function, making it easier to curry or partially apply the earlier arguments. Lodash/fp and ramda address this by having the following signature for map.

_.map(func, data);

If the function is curried, you can create specific versions of the function by only passing the first argument.

const double = x => x * 2;
const mapDouble = _.map(double);

mapDouble([1, 2, 3]);
// => [2, 4, 6]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related