Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.