# Setting Global var in a function using a variable name

**URL:** https://discourse.nodered.org/t/setting-global-var-in-a-function-using-a-variable-name/95817
**Category:** General
**Created:** [6 March 2025 00:53 UTC](https://discourse.nodered.org/t/setting-global-var-in-a-function-using-a-variable-name/95817 "2025-03-06T00:53:07Z")
**Posts on this page:** 5
**Page:** 1

<div class="post-metadata">

### Author: ![Pabliski](https://avatars.discourse-cdn.com/v4/letter/p/8edcca/32.png) [@Pabliski](https://discourse.nodered.org/u/Pabliski)
#### Post date: [6 March 2025 00:53 UTC](https://discourse.nodered.org/t/setting-global-var-in-a-function-using-a-variable-name/95817/1 "2025-03-06T00:53:08Z")

</div>

I found a similar [forum post](https://discourse.nodered.org/t/extract-a-substring-from-msg-payload-and-use-it-as-a-variable-for-global-set/77687) of what I am trying to do, yet, for me it is not working.  
I am on v4.0.9

```auto
let gname = msg.topic.split ("/")[1];

var OneZero="0";
if(msg.payload=="true") {
    OneZero="1";
}
global.set ( gname + ".State" , OneZero );
return msg;

```

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/4/0/40f0b0a122231dc5ecfe7cacb9e23814ccd82e90.png)

Injecting directly works. The function does not. I tried using "State." + gname and it did not do it either.

Help please.

---

<div class="post-metadata">

### Author: ![chrisn-au](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/chrisn-au/32/25504_2.png) [@chrisn-au](https://discourse.nodered.org/u/chrisn-au)
#### Post date: [6 March 2025 06:40 UTC](https://discourse.nodered.org/t/setting-global-var-in-a-function-using-a-variable-name/95817/2 "2025-03-06T06:40:27Z")

</div>

I have used Claude 3.7 to generate a response -\> including a test case (which I thought was quite cool)

I am not sure the rules in using AI to generate response however from my perpesctive this is an appropriate use of Claude. If it contravenes any rules feel free to delete

The answers seem sensible although the context on the global set seems out of whack however it appears to do no harm

[Claude response](https://claude.ai/share/b612bce4-f8ce-41c0-9fc5-5816c8494651)

You will notice at the bottom it has able to create a nice test flow. From my testing it appears work. I am not keen on it returning NULL so I have changed the code to return the unchanged msg (even that is not great)

**In case the link does not work and for longevity**

It looks like you're working with Node-RED or a similar flow-based programming environment. There are a few potential issues that could be causing your code not to work:

1. The most likely issue is with how you're accessing `msg.topic`. If `msg.topic` doesn't contain a "/" character or it's undefined, then `split("/")[1]` will return `undefined`.
2. You're setting a global variable with `global.set()` but you might be missing a context to attach it to.

Let me help you debug this. Here's a corrected version that includes error handling:

```auto
// First, validate that msg.topic exists and has the correct format
if (!msg.topic || !msg.topic.includes("/")) {
    node.error("Invalid msg.topic: " + msg.topic);
    return msg; // Exit the function early
}

// Extract the name from the topic
let gname = msg.topic.split("/")[1];

// Check if gname is valid
if (!gname) {
    node.error("Could not extract gname from msg.topic: " + msg.topic);
    return msg;
}

// Convert payload to "0" or "1"
let OneZero = (msg.payload === "true" || msg.payload === true) ? "1" : "0";

// Set the global variable
global.set(gname + ".State", OneZero);

// Debug output to help troubleshoot
node.log("Set global variable: " + gname + ".State = " + OneZero);

return msg;

```

---

<div class="post-metadata">

### Author: ![jbudd](https://avatars.discourse-cdn.com/v4/letter/j/5f8ce5/32.png) [@jbudd](https://discourse.nodered.org/u/jbudd)
#### Post date: [6 March 2025 07:18 UTC](https://discourse.nodered.org/t/setting-global-var-in-a-function-using-a-variable-name/95817/3 "2025-03-06T07:18:07Z")

</div>

> [@Pabliski](#):
>
> ```auto
> var OneZero="0";
> if(msg.payload=="true") {
> OneZero="1";
> }
> 
> ```

You are comparing msg.payload with a string "true". Are you certain that the data is not boolean `true`?

---

<div class="post-metadata">

### Author: ![Pabliski](https://avatars.discourse-cdn.com/v4/letter/p/8edcca/32.png) [@Pabliski](https://discourse.nodered.org/u/Pabliski)
#### Post date: [13 March 2025 11:42 UTC](https://discourse.nodered.org/t/setting-global-var-in-a-function-using-a-variable-name/95817/4 "2025-03-13T11:42:40Z")

</div>

Thank you for your suggestion. I found out what my disconnect was. I am using the [node-red-contrib-state](https://flows.nodered.org/node/node-red-contrib-state) which, it turns out, is not connected to the global variables (although I thought it was). I found the answer [here](https://github.com/lorenwest/node-red-contrib-state/issues/6#issuecomment-738117436).

Thank you for your ideas and help.

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)
#### Post date: [27 March 2025 11:43 UTC](https://discourse.nodered.org/t/setting-global-var-in-a-function-using-a-variable-name/95817/5 "2025-03-27T11:43:38Z")

</div>

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