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?
JavaScript
x
11
11
1
let fooVar = 3;
2
let barVar = "hello World";
3
4
function doStuff(variable) {
5
let varName = ???; // retrieve name of variable
6
return varName + ": " + variable;
7
}
8
9
document.write(doStuff(fooVar)); // should output "fooVar: 3"
10
document.write(doStuff(barVar)); // should output "barVar: hello World"
11
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.
Advertisement
Answer
That’s actually impossible to do, as a workaround you can do something like this
JavaScript
1
10
10
1
let fooVar = { name: 'fooVar', value: 3 };
2
let barVar = { name: 'barVar', value: 'Hello World' };
3
4
function doStuff({ name, value }) {
5
let varName = name; // retrieve name of variable
6
return varName + ": " + value;
7
}
8
9
console.log(doStuff(fooVar)); // should output "fooVar: 3"
10
console.log(doStuff(barVar));
or you can do
JavaScript
1
12
12
1
let fooVar = 3;
2
let barVar = 'Hello World';
3
4
function doStuff(variable) {
5
const arr = Object.entries(variable)[0];
6
const [name, value] = arr;
7
let varName = name; // retrieve name of variable
8
return varName + ": " + value;
9
}
10
11
console.log(doStuff({ fooVar })); // should output "fooVar: 3"
12
console.log(doStuff({ barVar }));