Bad form probably, but is this true about context variables

When I first started to use context variables, I was only saving primitives and so to change them I had sequences like this:

flow.set("stored number",1)
//other code
temp = flow.get("stored number")
temp = temp + 1
flow.set("stored number",temp)

This would cause the flow variable "stored number" to be created, populated with 1, then populated with 2.

I then learned about javascript passing objects including arrays by reference rather than by value. Thus when working with an object or an array, is the second flow.set redundant? If so, is it bad form to leave it out. Here is the sequence I am thinking:

flow.set("stored array",[1,2])
//other code
temp = flow.get("stored array")
temp.push(3)
// stored array is already [1,2,3] and so the following line is redundant
flow.set("stored array",temp)

I actually ran into problems with the pass by reference when storing objects, but an array was smaller code to show the question.

1 Like

Probably it is safer to add the final flow.set anyway. As you probably know there are mutating x non-mutating methods array methods. You may get confused if using non-mutating methods, like below:

flow.set("storedarray",["1","2"]);
//other code
temp = flow.get("storedarray");

node.warn(temp.concat("3"));
node.warn(temp.slice(1));

msg.payload = temp;
return msg;

There is a similar discussion here:

1 Like

Also if you decide at some point to use non-memory based context then the lack of the final set, may also come back to bite you..

2 Likes

This was very valuable to me as it showed how truly complex this area is. In particular, I got a lot of insight out of the youtube video you linked to in that other thread. I am quoting your message in that thread to help others come across it:

1 Like

Thanks for providing the additional reason to intentionally save back to the context variable. I hadn't investigated it, but it is good to know that non-memory (disk) based context works differently relative to assignments to other variables.

non-memory will also include database, cloud, network, and well as disk - ie anything that won't just accept a pointer reference...

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