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?