I have the example below of an impure function. Note the variable a
is outside of the function scope is being changed. To get around it, one could clone the object
Change the object:
function transformObject(a) {
Object.keys(a).forEach(function (k) { a[k] *= 2; });
}
var a = {
a : 1,
b : 2
};
transformObject(a);
document.write('' + JSON.stringify(a, 0, 4) + '
');
Keep the object and return a new object with the result:
function transformObject(a) {
var b = {};
Object.keys(a).forEach(function (k) { b[k] = a[k] * 2; });
return b;
}
var a = {
a : 1,
b : 2
},
b = transformObject(a);
document.write('' + JSON.stringify(a, 0, 4) + '
');
document.write('' + JSON.stringify(b, 0, 4) + '
');