Objects and Arrays
Objects and arrays are references. Know which methods mutate, which return new values, and how to copy safely.
Key points
- 1
Assigning an object or array copies the reference, not the value. Two variables can point at the same array.
- 2
conststops you reassigning a variable; it does not make the object immutable. - 3
Non-mutating methods (
map,filter,slice,concat,toSorted) return new arrays; mutating ones (push,splice,sort,reverse) change the original. - 4
Spread and
Object.assignmake shallow copies. UsestructuredClonefor deep copies that keep Dates, Maps and Sets. - 5
Object.freezeis shallow; nested objects stay mutable.
Common traps
JSON.parse(JSON.stringify(x))turns Dates into strings and dropsundefinedand functions.sort()sorts as strings by default:[10, 9, 1].sort()gives[1, 10, 9].
Read the source
Test yourself on Objects and Arrays
Ten questions, with the answer and explanation after each one.