Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save obengwilliam/017a5edd69b2634dca0b407344fd0ea6 to your computer and use it in GitHub Desktop.
Save obengwilliam/017a5edd69b2634dca0b407344fd0ea6 to your computer and use it in GitHub Desktop.
avoid mutation array and object using latest javascript

Array

Remove

list.splice(index, 1);

=>

list
.slice(0, index)
.concat(list.slice(index+1));

=>

[
  ...list.slice(0, index),
  ...list.slice(index+1)
];

Add

list[index]++

=>

list
.slice(0, index)
.concat([list[index]+1])
.concat(list.slice(index+1))

=>

[
  ...list.slice(0, index),
  list[index] + 1,
  ...list.slice(index+1)
];

Object

{
  id: todo.id,
  text: todo.text,
  completed: !todo.completed
}

=>

Object.assign({}, todo, {
  completed: !todo.completed
});

=>

{
  ...todo,
  completed: !todo.completed
}

Reference

  1. Redux: Avoiding Array Mutations with concat(), slice(), and ...spread - js Video Tutorial #free @eggheadio
  2. Redux: Avoiding Object Mutations with Object.assign() and ...spread - js Video Tutorial #free @eggheadio
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment