get variable name into string in javascript
Yes, you can do it:
function getVariableName(v) {
for (var key in window) {
if (window[key] === v)
return key;
}
}
var abc = '123';
var def = '456'
alert ("value of " + getVariableName(abc) +" is "+ abc +" and value of " + getVariableName(def) + " is " + def);
Use the code below.
const abc = '123';
const def = '456';
const varToString = varObj => Object.keys(varObj)[0]
alert ("value of " +varToString({def}) +" is "+ def +" and value of " +varToString({abc})+" is "+abc );
What this basicly does is, you pass the variable to varToString
as an object using {variable}
. varToString
then returns an array
with the passed variable as value.
[
"abc"
]
We grab this value using the [0]
selector (Object.keys(varObj)[0]). Now it returns
abc