Can you not set context variables by assignment?

I'm using global context variables to store an authorization token, but I've noticed that the value doesn't appear in the context sidebar unless I assign it using a Change node.

In the past I've simply assigned them as such:

global.auth_token = msg.payload.auth_token;

But the documentation seems to require the following:

global.set("auth_token", msg.payload.auth_token);

It seemed circuitous considering it accomplishes the same thing as variable assignment but with more code, so I planned on just sticking with variable assignment, but that doesn't seem to work any more.

What happened to simply assigning context variables? What's the benefit of using set()/get()?

If you were to decide to use file backed context (for persistence), the global.variable = "something" method wouldn't work (as the set function does the extra bits like persisting to file).

For consistency sake, I believe we should all be using global.set(...)

1 Like

get/set also allow you to get/update content within an object.

In the future, other persistence capabilities might be added as well and if you use get/set, you will be able to use those - potentially without any change to your code (e.g. if you were to change the default handler in settings.js).

Also, I'm not sure whether you might get some odd behaviours if assigning directly. This would be because JavaScript assigns by reference by default and so you aren't necessarily creating something new when you think you are but only a new reference to something already existing. Using set forces the variable to be something new I believe.