1. 9
    Redux: Avoiding Array Mutations with concat(), slice(), and ...spread
    3m 54s

Redux: Avoiding Array Mutations with concat(), slice(), and ...spread

InstructorDan Abramov

Share this video with your friends

Send Tweet

Learn how to avoid mutating arrays using concat(), slice(), and the ES6 array spread operator.

Sequoia McDowell
~ 9 years ago

Is there a library of non-mutative array methods? Rewriting versions of Array.prototype.splice over and over to avoid mutation seems a bit crazy. :p

Dan Abramovinstructor
~ 9 years ago

Check out https://github.com/kolodny/immutability-helper.

Christian
~ 7 years ago

Avoiding mutations is made way easier with Immutable JS:

const addCounter = list => {
  return list.push(0);
};

const removeCounter = (list, index) => {
  return list.remove(index);
};

const incrementCounter = (list, index) => {
  return list.update(index, i => i + 1);
};

const testAddCounter = () => {
  const listBefore = List();
  const listAfter = List([0]);
  expect(addCounter(listBefore)).toEqual(listAfter);
  expect(listBefore.size).toEqual(0);
};

const testRemoveCounter = () => {
  const listBefore = List([0, 10, 20]);
  const listAfter = List([0, 20]);
  expect(removeCounter(listBefore, 1)).toEqual(listAfter);
};

const testIncrementCounter = () => {
  const listBefore = List([0, 1, 2]);
  const listAfter = List([0, 1, 3]);
  expect(incrementCounter(listBefore, 2)).toEqual(listAfter);
};

testAddCounter();
testRemoveCounter();
testIncrementCounter();
console.info("all tests passed");
Charles Owen
~ 6 years ago

What are the performance tradeoffs for ensuring the immutability of an array with a large object graph, with potentially thousands of objects with nested objects within them? I'm assuming returning a new array builds an entirely new copy in memory or is it using pointers to the source array?

Team Authoring Learning Objects
~ 6 years ago

Just taking this course now; I get a deepFreeze is undefined error. However, I noticed Object.freeze is built in and gets the error I want.

Alex Okros
~ 6 years ago

Just taking this course now; I get a deepFreeze is undefined error. However, I noticed Object.freeze is built in and gets the error I want.

Just remember that if you need to make an object immutable, recursively freeze each property which is of type object (deep freeze). Otherwise you'll have a shallow freeze.