Skip to the content

Methods that change and methods that don't

JavaScript · Unit 15: Immutability

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. 1. Predict the output

    Two methods with similar names. What does it print?

  2. 2. Predict the output

    o looks like a sorted copy. What does it print?

  3. 3. Complete the code

    Fill in the blank to see the prices sorted without losing the order they arrived in.

  4. 4. Complete the code

    Fill in the blank to print the days backwards and keep d starting on mon.

  5. 5. Find the bug

    top2 should 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. 6. Multiple choice

    nums is an array of numbers. Which of these lines leaves it exactly as it was?

  7. 7. Predict the output

    filter returns a new array. What does it print?

  8. 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. 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. 10. Predict the output

    The function calls pop on what it receives. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →