get variable name into string in javascript

Viewed 20293
var abc = '123'

var def = '456'

need to write somefuntion() which convert variable name into string

like

alert ("value of" +somefuntion(abc) +"is"+ abc +"and value of" +somefuntion(def)+" is"+def );

should be like this

alert ("value of abc is 123 and value of def is 456")

i have searched and tried few solution and idk how this link can help cuz i know you will say its duplicate but i tried it and it didnt work

How to turn variable name into string in JS?

3 Answers

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

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

A neat way of doing this would be:

make an object as :

const data = {
    abc: {
        key: 'abc',
        value: '123',
    },
    def: {
        key: 'def',
        value: '456',
    }
}

and then when you want to access them, you can do :

alert ("value of" +data.abc.key +"is"+ data.abc.value  +"and value of" +data.def.key+" is"+data.def.value );

or

const abc = {key: 'abc', value: '123'};
const def = {key: 'def', value: '456'};

alert ("value of" +abc.key +"is"+ abc.value  +"and value of" +def.key+" is"+def.value );
Related