praine
praine

Reputation: 415

Declare a nodejs const from a variable?

Is it possible to programmatically declare a nodejs const from a variable (string?)

let myConsts = ["const1","const2","const3"];
myConsts.forEach(function(label){
defineConst(label,"value"); // I need this function
})

defineConst should define a const, something like the PHP "define" function, but for nodejs

Upvotes: 0

Views: 2471

Answers (1)

jfriend00
jfriend00

Reputation: 707326

No, you can't really do that in Javascript. For a bit, I thought maybe you could hack it with eval() which is pretty much always the wrong way to solve a programming problem, but even eval() won't introduce a new const variable to the current scope. It will introduce a new var variable to the current scope as in this:

// dynamic variable name
let varName = "test";

// create variable in the current scope
eval("var " + varName + " = 4;");

// see if that variable exists and has the expected value
console.log(test);

But, alas you can't do this with const. You can read more about why here: Define const variable using eval().

Whatever programming problem you are trying to solve can likely be solved in a much better way since you really shouldn't be introducing dynamically named local variables. It's much better to use something like a Map object or a regular object with dynamically named properties in order to keep track of values with dynamic names to them.

If you shared the actual programming problem you're trying to solve (rather than your attempted solution), we could advise further on the best code for that particular problem.


Here's an example of the ability to store dynamically named properties on an object:

let base = {};

// dynamic property name (any string value in this variable)
let varName = "test";

// set property value with dynamic property name
base[varName] = "Hello";

// can reference it either way
console.log(base[varName]);
console.log(base.test);


Or, it can be done using a Map object:

let base = new Map();

// dynamic Map element key (any string value in this variable)
let varName = "test";

// set Map element with dynamic key
base.set(varName, "Hello");

// can reference it either way by the key
console.log(base.get(varName));
console.log(base.get("test"));

Upvotes: 2

Related Questions