inthenameofmusik inthenameofmusik - 2 years ago 90
Javascript Question

Beginner JavaScript OOP vs Functional

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.[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.

Answer Source

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 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,;

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., 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 =;

mapDouble([1, 2, 3]);
// => [2, 4, 6]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download