Sara Ree
Sara Ree

Reputation: 3543

getting variable name which is a argument of the function as a string

I know we can get a variable name as a string like this:

const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName);

But I want to know if there is a solution in JavaScript to get the variable name set as a argument in a function?

function foo(variable) {

    const varToString = varObj => Object.keys(varObj)[0]
    const displayName = varToString({ variable })
    console.log(displayName);

}

const someVariable = ['string', 'another string'];
foo(someVariable);

As you see I get the internal variable name inside the function which is expected here... I want the original variable name instead so in this case we should get someVariable.

Is there any solution or I'm just wasting my time?

Upvotes: 0

Views: 63

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074425

I know we can get a variable name as a string like this:

That doesn't get a variable name. It gets a property name, which is inferred from a variable name elsewhere in the code.

But I want to know if there is a solution in JavaScript to get the variable name set as a argument in a function?

No. What's passed to the function is the value that came from the variable. There is nothing that connects that value back to the variable.

Upvotes: 1

Peter B
Peter B

Reputation: 24147

In the first snippet, varToString() is called with an object with a named property, and then you can retrieve the property name as you are doing already.

In the second snippet, foo() receives an array object without any information about where it came from; that is just how parameter passing works in javascript.
If you change that call to foo({ someVariable }) then you can make it work again, because then you have created a new object that has a named property.

Upvotes: 1

Related Questions