Methods that change and methods that don't
JavaScript · Unit 15: Immutability
- Full plan
- JavaScript
- 10 exercises
Array methods come in two kinds. push, pop, splice, sort and reverse change the original array; we say they mutate it.
map, filter and slice don't touch it: they hand you a new array.
const n = [3, 1, 2];
const twice = n.map((x) => x * 2);
n.push(9);
console.log(n, twice);Prints
[ 3, 1, 2, 9 ] [ 6, 2, 4 ]
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
Two methods with similar names. What does it print?
2. Predict the output
olooks like a sorted copy. What does it print?3. Complete the code
Fill in the blank to see the prices sorted without losing the order they arrived in.
4. Complete the code
Fill in the blank to print the days backwards and keep
dstarting on mon.5. Find the bug
top2should give the two highest scores without shuffling the list, so the last line should print the points just as they arrived. Which line has the error?6. Multiple choice
numsis an array of numbers. Which of these lines leaves it exactly as it was?7. Predict the output
filterreturns a new array. What does it print?8. Put the lines in order
Put the program in order: it stores the prices sorted and then adds one more to the list you already had.
9. Find the case that fails
secondLargest(nums)returns the second largest number in the list, without changing it, or 0 if the list only has one number. Which call does it fail on?10. Predict the output
The function calls
popon what it receives. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.