Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active March 20, 2021 03:39
Show Gist options
  • Save LeanSeverino1022/3e4aa65d3c73bbbd66f2cfe6565464cf to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/3e4aa65d3c73bbbd66f2cfe6565464cf to your computer and use it in GitHub Desktop.
Mutating vs. Non-Mutating Array methods #vanillajs

.reviewed

If an item is mutable, modifying the copy also modifies the original. If it’s immutable, modifying the copy does not affect the original. It’s confusing because immutable sounds like the item can’t be changed. What it actually means, though, is that the original is not changed when the copy is.

array.splice() mutates the original array, (changes the contents of an array) array.slice() does not mutate the original array (returns a shallow copy)

Adding items

Mutating: 'array.push() and array.unshift() Non-mutating: array.concat().

Removing

Mutating: array.pop() and array.shift() and array.splice() - it also returns the items it removed Non-Mutating: array.filter() , array.slice()

Replace

Mutating: If you know the index of the item you want to replace, you can use array.splice() non-Mutating:array.map()

Src and with more examples: https://lorenstewart.me/2017/01/22/javascript-array-methods-mutating-vs-non-mutating/

TODO: Helper function fior create an immutable copy of an array or object with vanilla JS

https://gomakethings.com/a-better-way-to-create-an-immutable-copy-of-an-array-or-object-with-vanilla-js/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment