Convert Boolean to Integer

Sorry to trouble you with such a basic JavaScript problem, but this is driving me CRAZY.

I need to convert a Boolean true/false into a numeric value for further processing. The flow I'm creating takes the Boolean from a msg.payload array, and involves multiple "if" checks on different elements in the array, but to simplify things I've reproduced the bit that isn't working in the attached sample.

The objective is to simply return one integer when the Boolean is "true" and a different one when it's "false" but I just can't get it to work.

Thanks in advance,

I

[{"id":"31261c3d.b8d2a4","type":"function","z":"e8716096.c220c","name":"","func":"if (msg.payload == \"true\") {\n msg.payload = 111;\n} else {\n msg.payload = 999;\n}\nreturn msg;","outputs":1,"noerr":0,"x":450,"y":200,"wires":[["e5e5b077.cc8d4"]]}]

So your function is ...

if (msg.payload == "true") {
 msg.payload = 111;
} else {
 msg.payload = 999;
}
return msg;

try...

node.warn(msg.payload)
msg.original = msg.payload;
if (msg.payload === "true" || msg.payload === true) {
 msg.payload = 111;
} else {
 msg.payload = 999;
}
return msg;

and show us the debug log.

1 Like

Many thanks for the prompt reply, and more importantly, thanks for fixing the function!

Your version works properly.

Much obliged.

You are not the first and certainly won't be the last to be tripped up by JavaScript == vs. ===

2 Likes

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