I was writing a Javascript program and part of the program state was an object. I want to periodically calculate the state and compare it to the current one to decide if an event should be triggered, here's some pseudo code:

```
var newState = calculateState();

if (newState !== oldState) {
  triggerEvent();
}

```

However since the state is an object I need to do a value equality check as well as guard against null reference check. That is, if the state becomes null from non null value or the other way around, I also need to trigger the event:

```
if (newState === null && oldState !== null ||  // non null -> null
    newState !== null && oldState === null ||  // null -> non null
    (newState !== null && oldState !== null &&  // both non null, check members
     (newState.age !== oldState.age ||
      newState.name !== oldState.name))) {
    triggerEvent();
}

```

As you can see the code is really messy and ugly.

Is there a way to refactor this in Javascript?

Thank you!