0

I have a Function in which I want to retrieve the name of the variable that was used to call the function. How can I do that?

let fooVar = 3;
let barVar = "hello World";

function doStuff(variable) {
    let varName = ???; // retrieve name of variable
    return varName + ": " + variable;
}

document.write(doStuff(fooVar)); // should output "fooVar: 3"
document.write(doStuff(barVar)); // should output "barVar: hello World"

If variable was a Function, I could use variable.name.

I am aware of this, but it will only return "variable", not the name of the variable that was put into the function.


As an alternative: Is there a way to AUTOMATICALLY call a certain function whenever a variable is declared? If that was possible, I'd use the approach given in the link above to add the variable name to a map, then utilize that map inside the function to retrieve variable name.

5
  • Does this answer your question? Variable name as a string in Javascript Commented Nov 3, 2021 at 12:40
  • @SimoneRossaini no. I linked an answer to that question and explained why it does not help. Commented Nov 3, 2021 at 12:46
  • Yes true, it's impossible because you change name of variable into function so you must use object Commented Nov 3, 2021 at 12:50
  • It's not possible to do what you wanted Commented Nov 3, 2021 at 12:52
  • The other question is "Why do you want to do this?" Commented Nov 3, 2021 at 13:04

1 Answer 1

1

That's actually impossible to do, as a workaround you can do something like this

let fooVar = { name: 'fooVar', value: 3 };
let barVar = { name: 'barVar', value: 'Hello World' };

function doStuff({ name, value }) {
    let varName = name; // retrieve name of variable
    return varName + ": " + value;
}

console.log(doStuff(fooVar)); // should output "fooVar: 3"
console.log(doStuff(barVar));

or you can do

let fooVar = 3;
let barVar = 'Hello World';

function doStuff(variable) {
    const arr = Object.entries(variable)[0];
    const [name, value] = arr;
    let varName = name; // retrieve name of variable
    return varName + ": " + value;
}

console.log(doStuff({ fooVar })); // should output "fooVar: 3"
console.log(doStuff({ barVar }));

Sign up to request clarification or add additional context in comments.

2 Comments

Second workaround solves my problem, thanks!
No problem, please consider marking it as a correct answer if it helped :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.