Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional-style JavaScript: good practice to avoid argument mutation?

This is a rather general question. Functional-style programming promotes the idea that a program is about transforming data through functions, and that mutation should be avoided (except possibly within a function, seen as a basic unit of abstraction).

But in this program:

function foo (bar) {
  bar.k1 = "bananas";
  return bar;
}

var o = { k1: "apples", k2: "oranges"};
var p = foo(o);

the external variable o is mutated within foo because bar is a reference to o, and, in the end, o === p (they reference the same object). But the functional paradigm would rather expect p to be fresh data.

The obvious solution is to clone the argument (e. g. using underscore/lodash's _.clone):

function foo (_bar) {
  var bar = _.clone(_bar);
  bar.k1 = "bananas";
  return bar;
}

But I wonder if this is the correct way to think about this problem. In a FP perspective, would you consider it a good practice to clone the objects passed as arguments if they will be mutated? (I am aware that not all objects can be cloned easily, if at all, but let's stick to simple cases). Your thoughts?

like image 991
Nicolas Le Thierry d'Ennequin Avatar asked Mar 01 '15 10:03

Nicolas Le Thierry d'Ennequin


1 Answers

Ideally the function should return a brand new object everytime it is called. Obviously for performance reasons it is not great, this is why persistent data structures exist. There are a few libraries for JS; immutable-js is arguably the most popular.

Otherwise mutating the object is fine, and in JS it is common practice, since not every project would immediately benefit from persistent data structures, plus the weight of the library.

Also note that in JavaScript everything is passed by value, but values themselves can hold references.

like image 128
elclanrs Avatar answered Oct 07 '22 14:10

elclanrs