-2

In the following example code, the function "getOriginalName" does not exist, but that is what I am looking for:

for(let variable of [var1, var2, var3]) {
    console.log("Value: " + variable);
    console.log("Name: " + getOriginalName(variable));
}

In my dreams, getOriginalName would return "var1", "var2" and "var3".

I know that you can access the name of variable "x" with:

varName = Object.keys({x})[0]

However, in my case this does not get me far, as the loop variable is called "variable" in each iteration. So is there no way to iterate over a list of variables and still get the name of these variables?

julvanu
  • 13
  • 3
  • 1
    What is the purpose of displaying a variable name that could, for example, be changed by your fellow programmer or gets minified? – Salman A May 25 '23 at 13:19
  • 1
    If you need the variable name, then you need to use an object. – epascarello May 25 '23 at 13:21
  • @SalmanA Of course the final application is not printing out values. This example code served as simplification to show my goal. Where it does get interesting to me is for example for URL params where you have to insert key and value. It just seemed very lengthy and redundant to me, to define objects containing value and variable name, if the variables are already defined in a proper naming sceme. Then the names are defined twice. But maybe you have a different view on that or, as it seems, it is impossible anyway. – julvanu May 25 '23 at 13:35

2 Answers2

0

Unfortunately, there is no built-in way to achieve this in JavaScript, as variable names are not accessible during runtime. However, you can work around this limitation by using an array of objects, where each object contains the variable name as a key and its value as the corresponding value. Here's an example:

const var1 = 'apple';
const var2 = 'banana';
const var3 = 'cherry';

const variables = [
  {name: 'var1', value: var1},
  {name: 'var2', value: var2},
  {name: 'var3', value: var3}
];

for (let obj of variables) {
  console.log('Value: ' + obj.value);
  console.log('Name: ' + obj.name);
}

This code will produce the following output:

Value: apple
Name: var1
Value: banana
Name: var2
Value: cherry
Name: var3

This workaround allows you to keep track of both the variable names and their values during iteration. Note that this approach requires you to manually create and maintain the variables array, which may not be ideal for all use cases.

petit
  • 1
  • 2
0

Based on your comment, you can use an object containing key value pairs:

let var1 = 1;
let var2 = 2;
let var3 = 3;

Object.entries({
  var1,
  var2,
  var3
}).forEach(([k, v]) => {
  console.log("Name: " + k);
  console.log("Value: " + v);
});
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • Keeping with the OP's `for of` -> `for (const [k,v] of Object.entries({var1, var2, var3})) {....` Makes it a little bit more future proof too, if later wants to use `async` stuff. – Keith May 25 '23 at 13:40