What is wrong with my function? Javascript "if" doesn't seem to work

Hi,

I admit I'm not javascript knowlegeable neither programmer.... I'm cutting/pasting pieces of code in order to make things work...

I'm trying to get a flow working but I can't understand what I'm doing wrong on this one....
Basically I'm using a function to perform some filtering based on "if" statements. While some of them work, there is one that is not working...

if(msg.device.ieeeAddr==="0x00124b00224350da")   // This one works
{
 if(msg.payload.contact==="false") // This one never works
 {
  record_object="Kitchen Door Opened. Node 119. Contact value: " + msg.payload.contact;
  Timestamp = Timestamp=(new Date()).toISOString();
 }
 else  // as alternative to the previous "if" statement, this one is always called.
 {
  record_object="Kitchen Door Closed. Node 119. Contact value: " + msg.payload.contact;
  Timestamp=Timestamp=(new Date()).toISOString();
 }
 record_string = Timestamp + "\n" + record_object;
 battery={
     Node: "119",
     Bat: msg.payload_raw.battery
     }
}

The function returns the message, which, by definition is wrong because if the contact value is "false", the message should be "Kitchen door Opened", not "Closed":

2021-01-25T21:42:56.578ZKitchen Door Closed. Node 119. Contact value: false

msg.payload:

{
"battery":100,
"battery_low":false,
"contact":false,
"linkquality":30,
"tamper":false,
"voltage":3100
}

msg.device:

{
"dateCode":"20191107",
"description":"Contact sensor",
"friendly_name":"SensorPortaCozinha",
"hardwareVersion":1,
"ieeeAddr":"0x00124b00224350da",
"lastSeen":1611610547344,
"manufacturerID":0,
"manufacturerName":"eWeLink",
"model":"SNZB-04",
"modelID":"DS01",
"networkAddress":4096,
"powerSource":"Battery",
"type":"EndDevice",
"vendor":"SONOFF",
"lastPayload":{"battery":100,
"battery_low":false,
"contact":false,
"linkquality":30,
"tamper":false,
"voltage":3100},
"homekit":{"ContactSensor":{"ContactSensorState":1},
"ContactSensor_Inverse":{"ContactSensorState":0},
"Battery":{"BatteryLevel":100,
"StatusLowBattery":0}}}

Any idea what am I doing wrong?
Cheers

Hi @jabss,

I 'think' you should replace if(msg.payload.contact==="false") by if(msg.payload.contact=="false") or if(msg.payload.contact===false).

Because === means "equal and the same type". But in your input message the "contact":false means it is type boolean, while `msg.payload.contact==="false"``means that you expect a string "false".

If you simply use ==, it checks whether the value is equal but not the type.

P.S. I haven't tested my theory ...
Bart

1 Like

Hi,

I had tried before with the two equals " == " but without success....
Haven't tried the true/false statement without the quotes ( " " ).
With two equals and the statement without quotes it works!

if(msg.payload.contact==false)

Thank you very much!

1 Like

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