Const not supported in UI based JS scripts

Just came across that const is not supported at top level in MainUI based JS scripts. Not sure what it means exactly but const is working when using it like this:

configuration: {}
  - id: "1"
      command: ON
      itemName: TestItem
    type: core.ItemCommandTrigger
conditions: []
  - inputs: {}
    id: "2"
      type: application/javascript
      script: >
        const debug = false;
        const rule = "Test";
        console.log("Rule:",rule,". Item:",event.itemName,". Value:",event.itemCommand);
        if (debug) utils.dumpObject(event);
    type: script.ScriptAction

Can somebody sched some light?

It’s a context issue:

1 Like

@JustinG has the heart of the matter but if you really want to use const and let, these can be used inside functions. So you could use the same trick as is used in transformations and wrap the whole thing in a function call.

(function(data) {
  const debug = false;

Interesting. Do you think there’s any performance benefit to this?

No, I doubt there is any performance benefit. There might even be a performance hit given one extra layer on the stack and the fact that all those consts and lets need to be instantiated every time the rule is called instead of vars being reused from one call to the next (which is why we can’t use const and let in the first place). Of course, on most decent machines any performance difference one way or the other will probably be unmeasurable.

But it does give you a little more control over the context that gets reused. Your function is a blank slate so all it has cluttering it’s scope is what gets passed in as arguments (in this case event). It also lets you code Script Actions/Conditions using JS best practices a bit more.

I personally don’t do this though. The benefits don’t seem great enough to deal with the extra indentation. :wink: But I’m far from a good JS coder.

1 Like