Conditionally Change Object in JavaScript

Here's how to conditionally update an object in JavaScript.

Mutation

If you have some condition that you need to check before updating a JavaScript object, you can do so by mutating the existing object, such as:

function update(obj) {
  if (condition()) {
    obj.b = 2
  }
  return obj
}

Copy

And you know, if you're mutating local state, no other process can access that state because it's local, in the stack frame of the function. But, as a matter of practice, and in order to avoid a class of potential mutation bugs, you might think about avoiding mutation.

That could be done like this:

function update(obj) {
  return {
    ...obj,
    ...(condition() && { b: 2 })
  }
}

Using the same syntax, here's some test output:

node
> { a: 1, ...(true && { b: 2 }) }
{ a: 1, b: 2 }
> { a: 1, ...(false && { b: 2 }) }
{ a: 1 }

The downside is that it has an increase of symbols. But, with a more-practiced functional eye, it's easily read.