!= operator that's robust to NaN data

Hi there, I’m putting a script together that updates local data from data from an API. Sometimes the data from the API isn’t in the right format, so I have to clean it up using valueOf(). My script loops through each entry and checks if any of three things have changed, and if any of them have changed, I want it to execute my code to update with the new data. For background, this is for a project helping incarcerated people. The conditional looks like so:

if (parsedNewDate.valueOf() != parsedOldDate.valueOf() ||
oldPrison != newPrison||
inmate.released) {

The trouble is that I’m working with a strict date field and some of the local data is blank. When the API returns a result that isn’t a date (like “UNKNOWN” or “LIFE”), I want it to act as if the old (null) and new (invalid) dates match. The trouble is that the valueOf function returns the current, blank value as NaN. I figured out how to set invalid new API data to return as NaN so they match. But in Javascript, NaN == NaN returns False, meaning NaN != NaN returns true, and my conditional thinks the code should run even if the other two conditionals return false. Is there another/better way to handle this?

This might be useful:

1 Like

That does look useful, but I’m not sure how to work it in in terms of operator precedence.

What I’m looking for is for my code to fire if the new location, date, OR status doesn’t match the stored location, date, OR status.

If, for example, someone has been transferred to a new location, but their date is invalid, I want to code to fire to update the location.

However, if the date is invalid, and the location and status have not changed, I want the code to continue to the next instance of the loop.

I know how to make that work with simple || operators as I wrote above, but to use Number.inNAN(), I think I’d need to work an && operator, and I’m not clear on how to arrange them properly. Would it be something like this?

if ((parsedNewDate.valueOf() != parsedOldDate.valueOf() && Number.isNaN(parsedNewDate.valueOf())==false) ||
oldPrison != newPrison||
inmate.released) {

EDIT: Tried the above and it worked. Thanks, @JeremyLT!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.