skip to Main Content

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


  1. 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:

    const envs = ['dev', 'test', 'uat', 'stage', 'prod'];
    const resEnvs = {};
    
    for (let i = 0; i < envs.length; i++) {
      resEnvs[envs[i]] = `prefix${envs[i]}`;
    }
    
    console.log(resEnvs);
    // And simply use them as per requirement.
    console.log(resEnvs.dev);
    Login or Signup to reply.
  2. If you’re in a web browser, your global scope is the window object. To write code that works everywhere, use the globalThis object, which will be the window object in the browser context, and the global object in node.js.

    for (let i=1; i<5; i++) globalThis[`value${i}`] = i
    
    console.log(value1, value2, value3, value4);
    
    ['value1', 'value2', 'value3', 'value4']
      .forEach(varName => console.log(`${varName} is ${globalThis[varName]}`))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search