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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With