Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
get name of input variable (like Function.name)

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 }));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!