Context is reset to default when input is 0

Im testing my function with a inject node of topic dim with payload values of 0 and 1.

the code is like:

node.warn("xx context.dimpre:" + context.dim);
context.dim = context.dim || 100.0;
node.warn("xx context.dimpost:" + context.dim);

if (msg.topic === 'dim')
context.dim = msg.payload;
node.warn("xx msg.topic " + msg.topic + " msg.payload:" + msg.payload);
node.warn("xx context.dim:" + context.dim);

When I send >0 everything is as expected, context.dim is persisting the value.
When I send a 0 then it stores the value first:
"xx context.dim:0"

But afterwards when the node gets triggered again from another msg the value changes to its init value:

16.4.2020, 00:05:03node: percent in 2 colorsfunction : (warn)

"xx context.dimpre:0"

16.4.2020, 00:05:03node: percent in 2 colorsfunction : (warn)

"xx context.dimpost:100"

Why is this happening?
Thank you for any hint

because of this line

context.dim = context.dim || 100.0;

When you set context.dim to 0, the next time it runs, it gets the 100.0

THE REASON IS... 0 == false

Do this instead...

if(context.dim == "undefined"){
  context.dim = 100.0 //init value ONLY if its undefined

NOTE: accessing context in this manner is depreciated (see the node red documentation on context.get, context.set)

understood, its a short circuit evaluation. Thank you

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