Why am I getting NaN?

I am trying to write a function to give me a running average of a sensor value, but no matter what I do, the output is NaN. Yes, I did discover the Mean Value node, so my math is superfluous. Except, I would like to know why I am getting a NaN output- just to learn what I did wrong.

//Put just the average moisture into the payload.
var moistureRaw = msg.moistureRaw;
var runningWet = node.get('runningWet') || 0;
runningWet = (runningWet + moistureRaw ) /2;
node.set('runningWet', runningWet);
msg.payload = runningWet;
return msg;
node.get('runningWet')

There is no node.get function. If you are trying to use the node-scoped context, then use context.get/set.

But I would have expected that to result in an obvious error message in the Debug sidebar telling you node.get is not a function.

Actually, my code uses globals, but I changed it at the last moment before posting the question because I knew someone would rail on me for using global.get and global.set for variables not needed in another flow.

So other than that foopas', why is my function sending a NaN? Like I said, the Mean Value node took care of my need to average the sensor readings, but I would like to know what's wrong with my code? (For future knowledge).

//Put just the average moisture into the payload.
var moistureRaw = msg.moistureRaw;
var runningWet = global.get('runningWet') || 0;
runningWet = (runningWet + moistureRaw ) /2;
global.set('runningWet', runningWet);
msg.payload = runningWet;
return msg;

It happens if msg.moistureRaw is undefined

You are correct. On a previous node I had moved msg.moistureRaw to payload.

Would this:
var moistureRaw = msg.moistureRaw || 0;
resolve an unidentified variable and prevent the NaN error?

(Not for this function, but for future reference).

It would with the important caveat that it would only work as you expect with a 0 on the right hand side.

There is a function to check whether a value is NaN:

https://www.w3schools.com/jsref/jsref_isnan.asp

1 Like

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