How do i compare the item state in javascript?

Hi,

i’m at a loss, it should bei simple…

How do i compare the item state in javascript?

My code:

var itemState = triggeringItem.state;

console.info("Fenster-Status = " + itemState);
console.info(itemState == "CLOSED");

The console output. First I opened the window, then I closed it again.

2025-02-24 16:41:37.695 [INFO ] [omation.script.ui.alarmLangesLueften] - Fenster-Status = OPEN
2025-02-24 16:41:37.701 [INFO ] [omation.script.ui.alarmLangesLueften] - false

2025-02-24 16:41:39.864 [INFO ] [omation.script.ui.alarmLangesLueften] - Fenster-Status = CLOSED
2025-02-24 16:41:39.866 [INFO ] [omation.script.ui.alarmLangesLueften] - false

What am I doing wrong?

Daniel :slight_smile:

What Item’s state? Or are you trying to use the event Object?

Which version of JS?

UI or file based?

Assuming JS Scripting and not Nashorn, to get the state of an Item you need to use the Item.

console.info("The state of MyItem = " + items.MyItem.state);
console.info("The numeric state of MyNumericItem = " +items.MyNumberItem.numericState);
console.info("The quantity state of MyUoMItem = " + items.MyUoMItem.quantityState);

See JavaScript Scripting - Automation | openHAB

If you are working with the event it differs depending on whether you are in the UI or files. In the UI we get the raw event Object meaning everything in it is a Java Object. Usually you’ll need to convert that data to a String.

console.info("The new state of the triggering Item is " + event.itemState.toString());
console.info("Window open status = " + event.itemState.toString() == "CLOSED");

See JavaScript Scripting - Automation | openHAB

In file based rules the event Object is converted to JS for easier use so there is no need to convert it to a String by calling toString().

console.info("The new state of triggering Item is " + event.newState);
console.info("Window open status = " + event.newState == "CLOSED");

See JavaScript Scripting - Automation | openHAB

Ah, sorry. I forgot to post the line for the item state. I’m using the JavaScript in a rule that I created through the UI (openHAB 4.3). I have added that in the original post.

console.info(itemState.toString() == "CLOSED");

As you wrote, it works with ‘toString()’!"

Best regards,
Daniel

Daniel, in these cases I would recommend you do yourself a favor, model it quickly in blockly and peek into the code :wink: