Is there a more efficient method for generating dynamic variable names from an array aside from using eval or document?

I need help figuring out how to create an array in JavaScript or TypeScript that contains a list of environment names. I want to iterate over this array and use the values as variable names within a closure.

My initial attempt looks like this (even though I know it 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 come across using eval as a solution:

let k = 'value';
let i = 0;
for i = 1; i < 5; i++ {
    eval('var ' + k + i + '= ' + i + ';');
}

This would result in:

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 an alternative method that does not involve using eval? I prefer to avoid eval because our code scanner flags it as a potential risk, resulting in constant explanations for false positives.

Edit To provide further clarification: I am aiming to create a variable that can be referenced later in my code. While the console.log examples showcase the values, I prioritize the ability to reference the name in subsequent code such as

newThing(envs[i] + i, other, params)
.

Additionally, I am steering away from utilizing items like window and document due to variations depending on where the code is executed.

Answer №1

To ensure better security and avoid relying on eval, you can store your variables in an object like this:

const environments = ['dev', 'test', 'uat', 'stage', 'prod'];
const environmentVariables = {};

for (let index = 0; index < environments.length; index++) {
  environmentVariables[environments[index]] = `prefix${environments[index]}`;
}

console.log(environmentVariables);
// Access the variables as needed.
console.log(environmentVariables.dev);

/* Update usage*/
function doSomething(env, otherValue, params) {
    console.log(`Environment: ${env}, Other Value: ${otherValue}, Parameters: ${params}`);
}

for (let index = 0; index < environments.length; index++) {
    doSomething(environmentVariables[environments[index]], 'anotherValue', 'parametersValue');
}


Update:

You can also retrieve values using bracket notation for looping or dynamic referencing:

console.log(environmentVariables['dev']); // "prefixdev"
console.log(environmentVariables['test']); // "prefixtest"

For the example of

doSomething(environments[i] + i, otherValue, parameters)
, you can use:

doSomething(environmentVariables[environments[i]], otherValue, parameters);

Answer №2

In the realm of web browsing, your overarching scope is embodied by the window entity. To ensure universal compatibility in your coding endeavors, utilize the globalThis entity, which assumes the guise of the window object within browser settings and the global entity within node.js environments.

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]}`))

Answer №3

Maybe this information could help you out with your query, if I've interpreted correctly, you might find the concept of Enums in TypeScript useful.

However, please be aware that this is relevant only if TypeScript is compatible with your project. A TypeScript enum will be converted into a JavaScript object during transpilation. Keep in mind: TypeScript enums can still be accessed from a regular JavaScript file (it will be recognized as an object).

Explore more here Further reading on TypeScript Enums

enum EnvironmentEnum {
  Dev = "Dev",
  Test = "Test",
  Prod = "Prod"
};

const Environments = Object.values(EnvironmentEnum);

// Output should be "Dev"
console.log(EnvironmentEnum.Dev);

// Output should be "Test"
console.log(EnvironmentEnum.Test);

// Logs the entire list
console.log(Environments);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble locating the error in my Angular and Spring Security application

I am currently working on a project that involves integrating Spring Security with an Angular client. I have encountered an issue where, despite checking for null values in the login form on the Angular side before sending it to the Java application, the J ...

How can I retrieve the value of a sibling's child using jQuery/Ajax?

I'm currently troubleshooting an AJAX comment feature that should activate when a user clicks "open comments." My PHP script is successfully returning data and the ajax call status is "200 OK," so it seems to be functional. However, I am struggling t ...

Ensuring Smooth Transfer: Sending Local Storage Data to MVC Controller

I'm attempting to send an array of strings from my local storage (key value) to an MVC controller. Here's the code I have so far: Inside the cshtml View file: <script> function getFavouriteBooks() { var ids = JSON.par ...

Node.js: Experiencing HTTP request timeout issues lasting for over a minute

Using Node.js (version 0.10.28), I encountered an issue when making an http.request to my Ruby API for a large amount of data. The request seems to time out and return a 404 error after only 1 minute. Interestingly, when using other methods like wget or jQ ...

The MUI Select component requires two clicks to open its menu if another Select component's menu is already open

I have been developing an application with two dropdowns (Select components) positioned next to each other, denoted as A and B. When A is open and the user intends to click on B to open it, I observed that in the default behavior of material UI, the user ...

Incorporating a new textfield in Codeigniter through a button/link activation

Currently, I am working on designing a request form for my website. I am facing an issue with creating a button that can dynamically add new input fields when clicked. Unfortunately, I am unsure of how to resolve this problem. Picture this: [ button ] A ...

The JavaScript array on its second usage had a length of '0', yet it still contained objects within it

About the Task: This task involves working with two arrays: arrNumber, which is a number array, and arrString, which is a string array. The goal is to create a list of objects using the values from arrNumber, where the object keys are numbers or characte ...

Center a span vertically inside a div as the text within the span grows to occupy the entire div

I am facing an issue with a table that has 25 td's. Each td contains specific elements as shown below: <td> <div> <span> text </span> </div> </td> Additionally, there is a script in place that adj ...

The provider named toasterProvider is not recognized within the dependency injection chain, which includes toaster, RugHttpInterceptor, $http, and ng1UIRouter

Working with Interceptors to show a toast message when my app encounters an HTTP error in responseError code. Using AngularJS Interceptor for an MEAN.JS app. Interceptor Code angular.module('rugCoPro') .factory('RugHttpInterceptor', ...

Issue with Component in Angular not functioning properly with proxy construct trap

Currently working with Angular 17, I have a straightforward decorator that wraps the target with Proxy and a basic Angular component: function proxyDecorator(target: any) { return new Proxy(target, { construct(target: any, argArray: any[], newTarget: ...

What is the most efficient way to retrieve the current user's ID within Loopback?

Given the instability and deprecation of loopback.getCurrentContext(), what strategies can I use to accurately identify users when they interact with API endpoints? Is it feasible to include the token ID in the request payload for verification purposes? H ...

Dealing with repeated parameters in a URLHow can you handle duplicate

My Ajax select input dynamically changes the URL without refreshing the page. However, I have encountered an issue where repeated parameters stack in the URL when the select input is changed multiple times: [domain]/find.php?cat=1#pricemin=10&pricem ...

I am experiencing difficulty with jQuery connecting to the elements on my server-generated webpage

My issue lies in using jQuery functionality within the Software AG webMethods IDE, where pages are generated automatically. I am providing jQuery's functions with a server-generated element ID, but it seems that jQuery is unable to interact with it - ...

Utilizing ngx-bootstrap to enhance Bootstrap dropdown functionality

I initially tried to set up ngx-bootstrap in Angular 2 by using the following command: npm install ngx-bootstrap bootstrap --save Then, I included these lines in angular-cli.json: "../node_modules/bootstrap/dist/css/bootstrap.min.css". In app.compone ...

Encountering a CORS policy error in Three.js when attempting to run locally

I'm just starting out on this website and I'm eager to dive into learning javascript. My initial attempt at following this example from resulted in an error without any animation or background showing up. Instead, all I see is a photo displayin ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Vue Labyrinthine Design theme

Looking for some guidance from experienced developers out there! I'm currently exploring how to incorporate Mazeletter as a background feature for each page in an app project I've been working on. This is all new territory for me, so any assista ...

PHP: Receiving notification if $_GET variable is void

When retrieving the array data, I use this code: $tags = $_GET['item']['tags']; if ($tags){ foreach ($tags as $tag){ The tags data is received from an input field, and it may be empty. If $tags does not receive any data, I enco ...

The transformation of a Blender model in THREE.js results in a completely new and distinct

I have a Blender model that I'm trying to integrate into my website using THREE.js, but I'm encountering issues with the GLTF file rendering. The model appears broken with missing elements, misplaced objects, and incorrect lighting. I've tes ...

Exploring Bootstrap4: Interactive Checkboxes and Labels

My form design relies on Bootstrap, featuring a checkbox and an associated label. I aim to change the checkbox value by clicking on it and allow the label text to be edited by clicking on the label. The issue I'm facing is that both elements trigger t ...