L05 Collections and mutation
16 minSuggested first: L04 Calls and returns
Outcome
Read an array index or object key and predict whether a change is visible through two names.
Learn
An array is an ordered collection, indexed from zero in JavaScript and Python. An object (a dictionary in Python) associates keys with values.
Two names can refer to the same collection. Updating a property changes the object itself, so
every name that refers to it sees the change. Assigning a new object to one name doesn't change
the other. In JavaScript, const stops a name being rebound, but it doesn't freeze the object.
Worked example
Draw an arrow from each name to the object it refers to, then predict what each update changes.
const cart = { counts: [1, 4] };
const alias = cart;
alias.counts[0] = 2;
const copy = { ...cart, counts: [...cart.counts] };
copy.counts[0] = 9;
Predict first, then show the worked explanation
Line 2 points alias at the original cart, so line 3 sets the original's first count to 2.
Line 4 makes copy a separate top-level object and a separate counts array, because both
were copied. Line 5 changes only the copy's array.
Practice and check
Common mistake
Treating spread (...) as a deep clone. For each property, ask which object it refers to.
Next
In the next lesson, trace what happens when the data isn't the type the code expects.
References
- JavaScript Guide (MDN)
- The Python Tutorial (Python documentation)