Undefined global variables

1,360 views
Skip to first unread message

Peter Scargill

unread,
May 27, 2016, 4:22:30 AM5/27/16
to Node-RED
And for today's daft question...

I want to know if a global variable exists... and I'm getting no-where.

if (global.get("fredsik")!==null) msg.payload=1; else msg.payload=0;
return msg;

I get 1 no matter what variable name I put in there... can someone put me out of my misery? What am I doing wrong?

Pete.

Giles Roadnight

unread,
May 27, 2016, 4:25:18 AM5/27/16
to Node-RED
you're doing a strict comparison with null so if it is undefined it will still be 1.

try 
global.get("variableName")!=null

--
http://nodered.org
 
Join us on Slack to continue the conversation: http://nodered.org/slack
---
You received this message because you are subscribed to the Google Groups "Node-RED" group.
To unsubscribe from this group and stop receiving emails from it, send an email to node-red+u...@googlegroups.com.
To post to this group, send email to node...@googlegroups.com.
Visit this group at https://groups.google.com/group/node-red.
For more options, visit https://groups.google.com/d/optout.

Peter Scargill

unread,
May 27, 2016, 4:27:59 AM5/27/16
to node...@googlegroups.com

You are in fact correct – thank you – mind you – node-red does gripe with a little triangle telling you not to do this. Would be nice to understand this more clearly.

 

Pete.

You received this message because you are subscribed to a topic in the Google Groups "Node-RED" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/node-red/DFoHJSBrhqE/unsubscribe.
To unsubscribe from this group and all its topics, send an email to node-red+u...@googlegroups.com.

Nicholas O'Leary

unread,
May 27, 2016, 4:34:15 AM5/27/16
to Node-RED Mailing List
JavaScript likes to make this sort of comparison non-obvious.

If you want to use a strict comparison (because using a non-strict comparison against null is discouraged), you should compare against undefined as that is what a non-existant value will return.

if (global.get("fredsik")===undefined) msg.payload=1; else msg.payload=0;

However, if you do global.set('fredisk',null) at any point, then the above comparison won't work any more, because it does have a value, it just happens to have a value of null.



Nick



Giles Roadnight

unread,
May 27, 2016, 4:47:19 AM5/27/16
to Node-RED Mailing List
you could of course do if (global.get("fredsik")!==null && global.get("fredisk")!==undefined)

Peter Scargill

unread,
May 27, 2016, 5:35:42 AM5/27/16
to node...@googlegroups.com

Thank you guys for today’s enlightenment. Excellent.

Reply all
Reply to author
Forward
0 new messages