Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the original name of loop variables in JavaScript?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading