Lessons · TypeScript · copy before you change it
Changing what was handed to you
Objects and arrays are passed by reference: changing one inside a function changes the caller's copy too.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
React not re-rendering, a 'copy' that changed the original, a shared config quietly edited by one module: all this.
How to think about it
Does the caller expect this unchanged? Treat parameters as read-only. If you need a changed version, build a new one: [...arr], {...obj}, arr.map(...).
Worked example
function addTax(cart) {cart belongs to the caller. return cart.map(i => ({ ...i, total: i.price * 1.2 }));New array, new objects. cart untouched.}
const taxed = addTax(cart);Both cart and taxed exist and differ.
Your turn
Return a copy with one item added, without changing the input.
function withItem(list, item) {
return [list, item];
}Solve one with the tests running
The trap
sort() and reverse() mutate in place. Use toSorted() and toReversed(), or copy first.
Practise copy before you change it on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.