Understanding mutation in common array methods - push and unshift
This series is about understanding what exactly happens to an array when we use common methods to manipulate the values. We'll learn which methods change (mutate) the original array, and which return a new copy. Mutation isn't inherently bad, but it can cause some interesting bugs if you modify something in a way that you weren't expecting.
Today we'll work to understand array mutation in the push and unshift array methods, and using spread syntax '...' instead of push or unshift.
Exercises
Try at least one exercise for each function, and try each exercise at least once. Most importantly, take the time to understand. Work as slowly and carefully as required to fully understand each step. Read the documentation links above. Take plenty of breaks. Don't rush.
Read the code, then answer
- What exactly does the function return?
- Does the function mutate the input array?
- Does the function return the same array or a new array?
Predict and trace
4. Predict exactly what each variable's value will be after each line of code executes. Then, verify your predictions by running the code and stepping through it in your dev tools debugger, or adding console.log.
Rewrite
5. Rewrite the code exactly, without copy paste. You can either look at the code while you re-type the same thing, or you could try rewriting it from memory, only referring back to the original to verify.
Test / Assert
6. Write a couple very simple unit tests that verify the expected behavior
Functions
Function 1: Array.push
function appendGuest(guests, name) {
guests.push(name);
return guests;
}
let guests = ['Rowan', 'Sage', 'Finley', 'River', 'Jordan'];
let guestsPlusOne = appendGuest(guests, 'Alex');
Function 2: Spread and append
function appendGuestViaSpread(guests, name) {
return [...guests, name];
}
let guests = ['Rowan', 'Sage', 'Finley', 'River', 'Jordan'];
let guestsPlusOne = appendGuestViaSpread(guests, 'Alex');
Function 3: Array.unshift
function prependGuest(guests, name) {
guests.unshift(name);
return guests;
}
let guests = ['Rowan', 'Sage', 'Finley', 'River', 'Jordan'];
let guestsPlusOne = prependGuest(guests, 'Kai');
Function 4: Prepend and spread
function prependGuestViaSpread(guests, name) {
return [name, ...guests];
}
let guests = ['Rowan', 'Sage', 'Finley', 'River', 'Jordan'];
let guestsPlusOne = prependGuestViaSpread(guests, 'Kai');
Good Job!
That's all for today! You can see the answers here, but make sure you do the work before you peek at the answers!