Question on global context & function behaviour

Hi,
I have a problem using context. Consider this flow:

[{"id":"c966d72c.b3b428","type":"function","z":"d4de0d13.1abea8","name":"get global dummy","func":"var dummy = global.get(\"dummy\")||10;\nmsg.payload = dummy;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":770,"y":300,"wires":[["375b567e.93a7d2"]]},{"id":"c069bc8e.88a7b8","type":"change","z":"d4de0d13.1abea8","name":"set global.dummy","rules":[{"t":"set","p":"dummy","pt":"global","to":"payload","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":530,"y":300,"wires":[["c966d72c.b3b428"]]},{"id":"cdadfa02.84ae4","type":"inject","z":"d4de0d13.1abea8","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"0","payloadType":"num","x":350,"y":280,"wires":[["c069bc8e.88a7b8"]]},{"id":"4b751bf8.bf39e4","type":"inject","z":"d4de0d13.1abea8","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"2","payloadType":"num","x":350,"y":320,"wires":[["c069bc8e.88a7b8"]]},{"id":"375b567e.93a7d2","type":"debug","z":"d4de0d13.1abea8","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":990,"y":300,"wires":[]},{"id":"235495da.cc389a","type":"inject","z":"d4de0d13.1abea8","name":"get global dummy","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":560,"y":180,"wires":[["c966d72c.b3b428"]]}]

I start with no global context "dummy".
When I try to get it, the functions defaults the value to 10:
var dummy = global.get("dummy")||10;

When I inject 2, global context is set to 2, the subsequent function yields 2. Ok.

But when I inject 0, the global value is set to 0, however, the function yields 10.

Why is this the case? I am not a JS expert and all I read so far was that "||10" is useful when the part to the left of it is undefined. Is that wrong?
How can I fix that?

Thanks in advance, Uwe

Not quite. It is useful when the left is a false-like value, which includes undefined. But it also includes the number 0, the empty string "" , null and actual Boolean false.

If 0 is a valid value, but you want the default to be non 0, then you'll need to do a more explicit test:

var dummy = global.get("dummy");
if (dummy === undefined) {
   dummy = 10;
}

Thanks for that super quick answer!

I bet this is something others trapped over, too, or will, particularly those discovering NR without proper JS background.
Ciao, Uwe

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