Unexpected indentifier in simple function

I am trying to write a simple function to toggle based on receipt of of a specific payload (a button press from a zigbeetomqtt capture of a sonoff button)

if (msg.payload=="single"){
 if (cur_state==0){
     cur_state=1;
     } else {
     cur_state=0;
     }
 }
}
msg.payload=cur_state;
return msg;

Where / how do I declare cur_state and am I returning the updated cur_state correctly - I suspect that msg.payload=cur_state; is not the correct syntax.

you need to create a context variable to hold the state between calls, something like:

var cur_state = context.get('cur_state')||0;

Then change the: cur_state = 1
to: context.set('cur_state', 1)
More details are here:
https://nodered.org/docs/user-guide/writing-functions

loyaltolex , in your example, you have an extra brace, it shouldn't be

if (msg.payload=="single"){
 if (cur_state==0){
     cur_state=1;
     } else {
     cur_state=0;
     }
 }
//}       remove this brace
msg.payload=cur_state;
return msg;

Thanks everyone! Here is the final code which works for me, reproduced for the benefit of others. Thanks and all credit for your input.

var cur_state = context.get('cur_state')||0;
if (msg.payload=="single"){
 if (cur_state===0){
     context.set('cur_state', 1);
     } else {
     context.set('cur_state', 0);
     }
 }
msg.payload=cur_state;
return msg;

Actually I just improved it by moving the msg.payload=cur_state; line back into the first if - resulting in the function passing the original payload unchanged if a switch press (a "single") was not the payload
Again the completed code for anyone interested [ is code ever complete? :slight_smile: ]

var cur_state = context.get('cur_state')||0;
if (msg.payload=="single"){
 if (cur_state===0){
     context.set('cur_state', 1);
     } else {
     context.set('cur_state', 0);
     }
msg.payload=cur_state;
}

return msg;

I believe you could get rid of the second if statement and use
Context.set(‘cur_state’,Math.abs(cur_state-1)
not at my computer to make sure Math is available