Object Oriented Programming vs. Functional Programming: Best Of Both Worlds

Victor Le Nerd
hello JS
Published in
2 min readSep 30, 2016

--

Javascript is flexible, we can code to suit certain number of programming paradigms whilst still maintain the standard, for instance redux is influenced by functional programming as well the observer pattern and it doesn’t require a change in syntax and semantics. As we already know functional programming is here to stay, It’s been around for a while and recently being adopted in Javascript to ensure our code is clean, testable, portable, memoizable and parallelizable.

On the other hand object oriented programming is what most Javascript applications have been built on. Languages like C++ or Java require strict construct to defining a class, however a class can be defined with object literal which is pretty simple.

Javascript uses dots notation and brackets notation for interacting with objects.

var box = {}box["material"] = "cardboard" //assign propertybox.material; //access property

While the dot and square bracket notation is very useful, it has certain limitations. For instance

function get(property, object) {  return object[property];}var people = [{name: …}, …];function getPersonName(person) {  return get(“name”, person);}var names = people.map(getPersonName);

The get function can be better by separating the arity from the function with a functional programming technique called currying.

function curry(fn) {  return function() {    if (fn.length > arguments.length) {      var slice = Array.prototype.slice;      var args = slice.apply(arguments);      return function () {        return fn.apply(          null, args.concat(slice.apply(arguments)));        }     }     return fn.apply(null, arguments);
}
}

Curry is a pure function that takes a function as an argument and keeps note of the arguments of the function if it is less than that of the original function and returns another function to collect the rest of the arguments, but pass the arguments to the original function if the number of arguments is more than that of the original function.

var get = curry(function (property, object ) {    return object[property];});var getName = get(“name”);var names = people.map(getName);

In conclusion, object oriented programming and functional programming can be complements of each other hence helping us build apps better.

--

--

I love to build beautiful digital products for startups and other enterprises. I write about coding, entrepreneurship and poetry.https://github.com/victorlenerd