I am looking for a way to create an array in js/ts that contains a list of environment names. I want to loop over that array and use the array value as variable names in the body of the closure.
I would like to do something like (I know this won’t work):
const envs = [ dev, test, uat, stage, prod ]
for (i = 1; i < envs.length; i++) {
const envs[i] = `prefix${envs[i]}`;
}
I have seen where you can use eval like:
let k = 'value';
let i = 0;
for (i = 1; i < 5; i++) {
eval('var ' + k + i + '= ' + i + ';');
}
Which would output:
console.log("value1=" + value1); // value1=1
console.log("value2=" + value2); // value2=2
console.log("value3=" + value3); // value3=3
console.log("value4=" + value4); // value4=4
Is there another way to do this without using eval? I know people will ask, so the reason I don’t want to use eval is that we use a code scanner that will flag the use of eval and we have to explain false positives constantly.
2
Answers
You can simply use an object to store your variables which would be much safer and you do not have to rely on
eval
. Something like:If you’re in a web browser, your global scope is the
window
object. To write code that works everywhere, use theglobalThis
object, which will be the window object in the browser context, and theglobal
object in node.js.