Trying to do something that should be straight forward but missing something... basic, and the tutorials I am looking at I feel they are not using variables the way I am doing it in a node
For simplicity I have node where I need to define a starting value once and then increment it. I have it working this way:
This is a function node then, and the scope of the context variable is just that node.
You are never saving the incremented testvar back to context.
var testVar = context.get('testVar') || 0 // Retrieve the con text variable, or else default to 0
testVar = testVar + 1 // Increment
context.set('testVar', testVar) // Save to context
msg = testVar // This is wrong. Should probably be msg.payload = testVar
return msg;
Note that you might have seen an example where a context variable holds an object
let car = context.get('car') || {"make": "ford", "model": "fiesta"}
car.model = "focus"
In this case the change will be saved if the variable exists, without an explicit context.set, though it's probably bad form to rely on that and not call context.set.
Yes, though I tend not to do that for simple cases like this. I tend to forget that On Start is there and when I look at the code in On Message it looks as if the context variable is not initialised, so I usually just use testVar let testVar = context.get('testVar') ?? 0
Note that nowadays let and const are preferred over var, google will tell you why if you are interested. Also the newer operator ?? is to be preferred over || in this situation as it specifically checks for null or undefined. Keep || for boolean expressions.
As far as I can recall I never use On Start for that or anything else.
It makes sense to me for the declaration of a variable to be visible in the same editor window as it's use.
Easy enough for you to try it and report back!
Edit - If you put context.set(ātestVarā,100) into On Start, every time a message arrives at the node, testVar will be set to 100, probably defeating the purpose of using a context variable - to save values from one message to the next.