Variable name as a string in Javascript

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"

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

In ES6, you could write something like:

let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
  for(let varName in nameObject) {
    return varName;
  }
}
let varName = getVarNameFromObject(nameObject);

Not really the best looking thing, but it gets the job done.

This leverages ES6's object destructuring.

More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/


var x = 2;
for(o in window){ 
   if(window[o] === x){
      alert(o);
   }
}

However, I think you should do like "karim79"