Why is the global variable changing?

Hi!
I have written a function that should compare json msg.a and msg.b . The differences are displayed in msg.c. And msg.b is updated with values from msg.a . But I take these values from global variables 1 and 2. After my function is executed, I get the correct result. But, the global variable 2 is updated without my participation, without global.set . how is this possible? Why is this happening? For example, I recorded a video - Youtube
The code of my function

msg.c = {};
for (let key in msg.a) {
if (msg.b.hasOwnProperty(key)) {
if (msg.a[key] !== msg.b[key]) {
msg.c[key] = msg.a[key];
msg.b[key] = msg.a[key];
}
} else {
msg.c[key] = msg.a[key];
msg.b[key] = msg.a[key];
}
}
return msg;

My flow in attach
flows.json (4.8 KB)

Sorry, but I took one look at your flow, and was dizzy!

  • Copy this to that
  • Copy that to this
  • Set this to that
  • Set that to this

:dizzy_face:

But as a hint: objects are pass-by-ref - meaning, if its not a primitive type (string, int etc etc)

The object(s) you are referencing are only passing you the address (in memory) to that object.

so if anything is updating an object (and not a primitive type) its will update that object - no matter where it is in your code/flow

you might need to look at

RED.util.cloneMessage(<Object>);

This creates an un-attached copy of the original object, meaning manipulating it's result, wont alter the original one in your global reference

This is normal for javascript - and isn't a Node RED "possible-bug"

1 Like

Hello! thanks for your reply. If I understood you correctly, when I do msg.b = global.get(2), I get not a new object with the same data, but a reference to the global object? And when I make changes to the object msg.b, am I actually changing the global object as well? Then how can I make sure that the global object does not change without my instructions (global.set)?

Correct!

So do something like

msg.b = RED.util.cloneMessage(global.get(2))

So any (future) changes to msg.b are not applied to the global version , but only applied to the cloned copy

1 Like

I understand you, thank you for your time and for the sample code. Thanks!

1 Like

Note : This only applies to objects
(references to something that isn't a simple type : string, number etc)

simple things are pass-by-val as opposed to pass-by-ref

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