Skip to content

Instantly share code, notes, and snippets.

@lujanfernaud
Last active February 2, 2019 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lujanfernaud/d37c62940ab8bd2f41f48a8572e9b15a to your computer and use it in GitHub Desktop.
Save lujanfernaud/d37c62940ab8bd2f41f48a8572e9b15a to your computer and use it in GitHub Desktop.
Javascript: Avoiding Mutations the Easy Way

JavaScript: Avoiding Mutations the Easy Way

Removing an Element from an Array

// Bad:
list.pop()

// Good:
list.filter(element => element !== 'hi')

Adding an Element to an Array

// Bad:
list.push('hi')

// Good:
[ ...list, 'hi' ]

// Good:
list.concat(['hi'])

Replacing an Element in an Array

// Bad:
list[0] = 'hi'

// Good:
list.map(element => element === 'hi' ? 'bye' : element)

Updating a Property in an Object

// Bad:
person.name = 'Sam'

// Good:
{ ...person, name: 'Sam' }

// Good:
Object.assign({}, person, { name: 'George' })

Adding a Property to an Object

// Bad:
person.age = 30

// Good:
{ ...person, age: 30 }

// Good:
Object.assign({}, person, { age: 30 })

Removing a Property from an Object

// Bad:
delete person.name

// Good (sort of):
{ ...person, age: undefined }

// Good (using lodash):
_.omit(person, 'age')

Resources

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