Search code examples
javascriptglobal-variables

Appending a value to a global variable name calling it later


I know how to append a string with a value passed by and show it like this:

function(value) {
   console.log("New " + value);
}

The thing is: I'm attempting to append a value to a global variable and then call it together like this:

function(value) {
   console.log(value + globalvariable);
}

But it's not working because it doesn't call the whole thing it just append the value as a string and then call the globalvariable alone.

How can I append this value to the globalvariable as a globalvariable name altogether, to be able to call it later?

I'm a self-taught person and i dunno if I'm doing this wrong?

Maybe there's another better way to proper do this that i will be awesomely grateful to see

I have already tried a bunch of things that doesn't seem to work

I apologize if i writed a duplicate


Solution

  • As suggested here Dynamically create variable in javascript and assign value

    You can do this:

    var globalVar = 5;
    function test(value) {window[value+''+globalVar] = 'newValue';}
    
    test("myName");
    
    console.log(myName5);