NaN Got Me
Today I modified the script I had made for cleaning and correlating the
Reef Doctor fisheries data to calculate catch weight per fishing gear. A quick
job, I modified the final catch processing script to add up the weights per
gear and set it running.
Looking at the log file and the generated JSON, I noticed that the weights
were only showing up as null. A quick glance at the code, it all looked fine,
so I tried running it again to make sure I wasn’t going crazy. Sure enough, I
wasn’t. Enter rubber duck.
So for every trip, if the trip has catch data, I go through catch items,
determining the gear used for the catch item, then adding the weights to the
catch gear weight.
|
|
A quick glances at the additions didn’t come up with anything - how were they
coming up with and answer of null? The answer was the initiation (or lack
thereof the gear weight:
|
|
This, of course what not what I was meaning, missing out the typeof operator,
so the gear weight was never being initialised. Adding a number to undefined
results in NaN, which can then be added to as much as you like without a
change in value.
stringifying the resultant gear weight resulted in the tricksy (censored)null value in JSON.
|
|