Copy-on-write is a data-management technique for preserving immutability in a mutable language. Instead of changing the original value, make a copy, modify the copy, and return it. section 6.20 section 6.3
Apply the discipline in three steps:
- Make a shallow copy of the data you need to modify. section 6.3 section 7.8
- Modify only the copy inside the function. section 6.4
- Return the copy and assign it where the updated value is needed. section 6.4 section 6.7
- For nested data, copy the changed inner value and every container between it and the top-level value. section 6.16
Adding an element without changing the original
function add_element_last(array, elem) { var new_array = array.slice(); new_array.push(elem); return new_array; } The original array remains unchanged, while the returned array contains the new element. The same pattern can support array updates, object updates, and reusable wrappers such as withArrayCopy(). section 6.3 section 11.3
function arraySet(array, idx, value) {
return withArrayCopy(array, function(copy) {
copy[idx] = value;
});
}
function withArrayCopy(array, modify) { #1
var copy = array.slice();
modify(copy);
return copy;
}
A callback-based wrapper isolates the copy-and-return parts of the discipline while allowing the modification to vary. section 11.3




