Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericelliott/a241e58ea519c324700e to your computer and use it in GitHub Desktop.
Save ericelliott/a241e58ea519c324700e to your computer and use it in GitHub Desktop.

Do u have an example of FP vs OOP? tweet

Any example would be contrived, and will not adequately illustrate the fundamental philosophical differences between OOP and functional programming. For much more on pros and cons of OOP vs Functional programming, see "The Two Pillars of JavaScript" Part 1 (OOP) and Part 2 (Functional Programming).

OOP collection.append():

var collection = function collection(arr) {
  return {
    elements: [].slice.call(arr || []),
    append: function append(arr) {
      this.elements = this.elements.concat(arr || []);
      return this;
    }
  };
};

var a = collection([1,2,3]);

var b = a.append(['a', 'b', 'c']);

console.log(a, b);
/*
A: { elements: [ 1, 2, 3, 'a', 'b', 'c' ],
  append: [Function: append] }
B: { elements: [ 1, 2, 3, 'a', 'b', 'c' ],
  append: [Function: append] }
*/

console.log(b === a); // true

Functional collection.append():

var collection = function collection(arr) {
  return {
    elements: [].slice.call(arr || []),
    append: function append(arr) {
      var newCollection = this.elements.concat(arr || []);
      return collection(newCollection);
    }
  };
};

var a = collection([1,2,3]);

var b = a.append(['a', 'b', 'c']);
console.log(a, b);
/*
A: { elements: [ 1, 2, 3 ], append: [Function: append] }
B: { elements: [ 1, 2, 3, 'a', 'b', 'c' ],
  append: [Function: append] }
*/

console.log(b === a); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment