Javascript: Server sided dynamic variable names

17,350

Solution 1

Generally you would do something like:

var myVariables = {};
var variableName = 'foo';

myVariables[variableName] = 42;
myVariables.foo // = 42

Solution 2

In node.js there is the global context, which is the equivalent of the window context in client-side js. Declaring a variable outside of any closure/function/module as you would in plain Javascript will make it reside in the global context, that is, as a property of global.

I understand from your question that you want something akin to the following:

var something = 42;
var varname = "something";
console.log(window[varname]);

This in node.js would become:

var something = 42;
var varname = "something";
console.log(global[varname]);

Solution 3

Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.

var type = 'article';
this[type+'_count'] = 1000;  // in a function we use "this";
alert(article_count);
Share:
17,350

Related videos on Youtube

hexacyanide
Author by

hexacyanide

I work on the Google Cloud Platform.

Updated on September 16, 2022

Comments

  • hexacyanide
    hexacyanide over 1 year

    How would I create dynamic variable names in NodeJS? Some examples say to store in the window variable, but I was assuming that is client-side Javascript. Correct me if I'm wrong.

  • Bill
    Bill over 11 years
    I know this is what he was hinting at in the question, but putting things in the global namespace is frowned upon in node. You won't find many libraries that do this kind of thing.
  • Mahn
    Mahn over 11 years
    @Bill correct, but I was under the impression OP was confused at the lack of the window context in node.js and would like to know an equivalent.
  • jonathanKingston
    jonathanKingston over 11 years
    Perhaps using "runInThisContext" with the vm module in node would be slightly preferred? davidmclifton.com/2011/08/18/node-js-virtual-machine-vm-usag‌​e
  • andcl
    andcl almost 5 years
    Wrapping variable names into a standard object. Yes, very smart and clever :)
  • Nathan Boaldin
    Nathan Boaldin almost 4 years