Unexpected behavior when storing an array in a flow context variable

Hello,

I'm trying to create a flow context variable in a Function Node to store an array which will be dynamically filled or emptied according to some logic. Unfortunately, it seems that the context variable does not work as I was expecting.

This is a minimal code to reproduce what I'm trying to do:

//Set the flow var with an empty array
flow.set("test_var", [])

// Update the flow variable
flow.set("test_var", flow.get("test_var").push(5))

// Store flow var in msg.payload
msg.payload = flow.get("test_var")
return msg;

Looking at the code, I was expecting my msg.payload equal to [5] but, the returned result is a number (1).

What I'm doing wrong ?

Thank you in advance for your help.

Filippo

You are storing the result of push.

From mdn...

Return value

The new length property of the object upon which the method was called.

1 Like

The return value of javascript's push is the new length of the array, and this what you are then setting to test_var again.

If you store an object in flow context, you don't need to keep storing it every time you change it. So your code can be simplified to:

flow.set("test_var", [])

// Update the flow variable
flow.get("test_var").push(5)

// Store flow var in msg.payload
msg.payload = flow.get("test_var")
return msg;

That only applies for the default memory based context. Generally it is good practice to store it back. If a switch was made to using persistent storage (or other storage mechanism) then it may not work reliably if it is not written back after updating.

1 Like

Things are more clearer now.
Thank you all for your explanations.

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