If then else, elseif

I am trying to use three x if statements, without an else.
I seem to be struggling though. I think I probably ought to be using elseif but not sure how.
My 2xflow variables are set to 0 in a separate function node.
Can anyone offer assitance?

//declare state and count variable
var state = flow.get("redstate21");
var count = flow.get("redcount21");

//check to see that state has not changed
If(msg.payload = state)
{
    msg.payload = count;
}

//if payload is 0 and state was 1, do nothing 
   If(msg.payload < state)
    flow.set('redstate21', 0)
{
    msg.payload = count;
}

//if payload is 1 but state was 0, increase count by 1
 If(msg.payload > state)
 { 
    //increase the count by 1
    msg.payload = count+1
    //increase the flow,redcount21 variable by 1
    flow.set('redcount21', count);
    // record current state
    flow.set('redstate21', 1)
 }
 return msg;

Replace "If" with "if" everywhere.

if (msg.payload = state) makes payload equal to state.
The test for equality is ==

Because you are not specifying a default value for state and count, if those variables do not exist, you may get unexpected results.

try
let count = flow.get("redcount21") ?? 0

1 Like

Javascript does not have elsif, just use else and if together

if (msg.payload == state) {
  ...
} else if (msg.payload < state) {
  ...
} else {
  ...
}

I think that syntax only works with later versions of nodejs. Possible 18+ I am not sure. If it doesn't then
let count = flow.get("redcount21") || 0
will do the job.

msg.payload = count;

This will create a reference problem as you are overwriting msg.payload

Perhaps it is easier to describe what you want your flow to do and what the input is and the expected output.

The nullish coalescing operator was introduced in ES2020, the nullish coalescing operator isn't supported in Node.js 12 and below.

1 Like

I have a node which only outputs either a 1 or 0. And I would like to do a cumulative count every time that node switches from a 0 to 1 output but not if it changes from a 1 to 0.

Look at the RBE / Filter node. It permits data to pass when it changes.
Therefore if you pass this through an RBE it will only permit the msg to pass when it is different to the last msg. Then you can test its value to see if it is 1.

node that outputs 1 or 0 :point_right: RBE node :point_right: Switch node (test value is 1) :point_right: counter node.

There are lots of counter nodes in the palette manager or if your Node-RED is new enough, the debug node can be used as a counter.

Demo
image

Demo Flow (use CTRL+I to import)

[{"id":"a4466d60c511231a","type":"inject","z":"FFF0000000000001","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"0","payloadType":"num","x":310,"y":460,"wires":[["3650cccef22fb776"]]},{"id":"9bc308a84c877216","type":"inject","z":"FFF0000000000001","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"1","payloadType":"num","x":310,"y":500,"wires":[["3650cccef22fb776"]]},{"id":"3650cccef22fb776","type":"rbe","z":"FFF0000000000001","name":"","func":"rbe","gap":"","start":"","inout":"out","septopics":false,"property":"payload","topi":"topic","x":450,"y":480,"wires":[["0dec3153bc4c3759"]]},{"id":"0dec3153bc4c3759","type":"switch","z":"FFF0000000000001","name":"payload == 1?","property":"payload","propertyType":"msg","rules":[{"t":"eq","v":"1","vt":"str"}],"checkall":"true","repair":false,"outputs":1,"x":610,"y":480,"wires":[["41e04ad8caeb0a61"]]},{"id":"41e04ad8caeb0a61","type":"debug","z":"FFF0000000000001","name":"counter","active":true,"tosidebar":true,"console":false,"tostatus":true,"complete":"payload","targetType":"msg","statusVal":"","statusType":"counter","x":600,"y":540,"wires":[]}]

Wow, time passes so quickly.

Not really. The test for equality is ===. 3 = not 2. Using 2 = is "sort of equal" and should only be used when you really need it. Typically if your input might be an actual number or a number as a string. Otherwise it can easily introduce very hard to identify bugs and edge cases.

How true. Especially as node.js v16 is about to pass into the long goodnight. It expires in September.

Unfortunately, Node-RED has fallen somewhat behind.

There are some very interesting changes coming to Node.js soon, such as these:

  • v14 - optional chaining, Nullish Coalescing operators, String.prototype.matchAll,
    Intl.DisplayNames, Intl.DateTimeFormat, (Experimental: Async Local Storage, Top-Level Await, Diagnostic report), WeakReferences, private class methods
  • v15 - logical assignment operators, String.prototype.replaceAll, Promise.any, AggregateError, AbortController, (Experimental Promisified setTimeout/setImmediate)
  • v16 - Promisified setTimeout/setImmediate, RegExp match indices. npm v7 (peer deps now installed again). fs.rmdir no longer supports recursive (use new fs.rm)
  • v17 - OpenSSL 3 (incl QUIC), Readline Promise API
  • v18 - (Experimental: Fetch API, Web Streams API, Test Runner), HTTP Timeouts, findLast/findLastIndex array methods, Improvements to the Intl.Locale API [calendars, collations, hourCycles, numberingSystems, timeZones, textInfo, weekInfo], Intl.supportedValuesOf function

Dammit did i miss out an equals?

These shaky old digits cannot be relied on to oscilate at a reliable frequency! :upside_down_face:

1 Like

I usually blame the keyboard, the digits are fine!

Yes, you’re right

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