Variable name as a string in Javascript
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
Like Seth's answer, but uses Object.keys()
instead:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"