I am trying to figure out why the outcome of the “if-statement” below is the same no matter if the virtual switch item is set to “ON” or “OFF”. What am I doing wrong?
I am using OpenHAB4. Obviously, the code below is just an example.
Any help appreciated, thanks.
var value10 = items.getItem(‘vOfficeHeating’).rawState;
console.info(value10)
if (value10 !== “ON”) {
console.info(“This code runs because value10 is not set to ‘ON’”);
} else {
console.info(“This code runs because value10 is set to ‘ON’”);
}
If “ON”:
2024-01-28 22:54:40.208 [INFO ] [nhab.automation.script.ui.b7d527c792] - ON
2024-01-28 22:54:40.209 [INFO ] [nhab.automation.script.ui.b7d527c792] - This code runs because value10 is not set to ‘ON’
If “OFF”:
2024-01-28 22:56:16.608 [INFO ] [nhab.automation.script.ui.b7d527c792] - OFF
2024-01-28 22:56:16.609 [INFO ] [nhab.automation.script.ui.b7d527c792] - This code runs because value10 is not set to ‘ON’
rawState returns the actual java type of the item state (in this case most likely OnOff Type). When you send that to the console it will print as if it were a string, but it is definitely not a string ( you can try console.log(typeof(value10)) to see this for yourself. Because it is not a string, value10 !== “ON” will always evaluate to true, as !== compares both value AND object type (OnOff type always does not equal string type).
Unless there is some very specific reason, you should never need to resort to rawState in your rules. Just use state instead as @laursen demonstrated. That always returns the state in a string format so you can easily control your types and in this case compare the state to 'ON'successfully.
A corollary to this is that you should probably avoid === and !== in most cases as well, again, unless you really mean it and know exactly what types are possible in your expressions. Just use == and != instead. The latter two do have some limited capacity to do automatic type conversion (although I don’t believe it would work in this case).