Explanation of code help

@cymplecy posted this code back in January

if (msg.payload == 1) {
    msg.payload = 1 * context.get("previousState");
    return msg;

I have used this a number of times now and spent the better part of a day googling as to how it worked. I figure if I'm going to use a lot I should understand it. Unfortunately, my google searches all point back to the forum so I am left with no explanation. If someone could please tell me what is happening I would appreciate it.

So what happens is the following, if msg.payload == 1.

in the first line:


First you get previousState variable from the node context. The content of the is negated by ! - so you have instead of true, false or vice versa. So it acts like a toggle switch. The opposite value is then immediately stored again in the node-context.

The next line:

msg.payload = 1 * context.get("previousState");

As boolean true evaluates to 1 and false to 0 the result is 0 or 1.

To be honest I think the code is in my opinion a little bit laborious.

In my opinion it would be sufficient to use only booleans.

Thanks for the help

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