Don't really understand the behavior of a global variable

Hello everyone,

I'm beginner and it seems that I don't really understand how the global variables work...

In a project, I initialize a variable this way in a function node :

var example = [];
global.set("example",example);

But, in an other node, I try to do something like this :

example = global.get("example");
test = 2;
example.push(test);

But when doing this, it seems that my global variable "example" is modified, without using global.set.

And I really don't get it... In my case, it's useful, but I don't know how to explain and would like to understand !

Thanks a lot :slight_smile:

Object in javascript are passed by reference so when you
example = global.get("examnple")
The var example references the same memory as the global var example. So when you alter one you alter the same memory, hence all references to that memory will be the same.

you can use RED.util.copyMessage to clone a message @node-red/util_util - Documentation

2 Likes

Oh okay, that's why it's not the same behavior with an int, it's because it's not an Object but a primitive ! I thought an array wasn't really an object :slight_smile:

Thank you !

1 Like

Thank you for actually learning. - thats rare!

2 Likes

Note that it is still good practice to do global.set(). The reason is that if, for example, you use persistent context (so the data are saved between node-red restarts) then node-red uses the set to know that you have changed it so the value must be written to the file the next time the cache is written out.

3 Likes

Thank you marcus_j_davies for your nice comment ! :slight_smile:

Colin, ok ! Thanks for the precision ! I don't need persistent context in my case, but it's good to know !

1 Like

In 5 years time you might decide that you do, and then might have great difficulty trying to find why the persistent is intermittent.

Also note that it is generally considered best practice to minimise the use of flow and global context. It is very rare to have to use global or flow context. It is usually best to pass data with messages, which is what node red is all about.

1 Like

Using set/get for globals isn't just about persistence per se. It is about which library is being used to read/write context. There are several available libraries and most require you to use set or they won't work.

So please do always use it. Even the current use with in-memory context is not guaranteed to work in the future. For example, if a future version of Node-RED were to implement change events on context variables, the direct access methods might well stop working.

2 Likes

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