Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable name as a string in Javascript

Tags:

javascript

People also ask

Can a variable be a string JavaScript?

Variables in JavaScript are named containers that store a value, using the keywords var , const or let . We can assign the value of a string to a named variable.

Can you use a string to name a variable?

If we are given a string as input in our program, we can define a variable name with the string by adding the input string as a key into the symbol table. We can add a single character, numeric values, or strings as the associated value to the variable.

What is a string variable name?

A string variable is a variable that holds a character string. It is a section of memory that has been given a name by the programmer. The name looks like those variable names you have seen so far, except that the name of a string variable ends with a dollar sign, $. The $ is part of the name.


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"


This works for basic expressions

const nameof = exp => exp.toString().match(/[.](\w+)/)[1];

Example

nameof(() => options.displaySize);

Snippet:

var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);

Probably pop would be better than indexing with [0], for safety (variable might be null).

const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${variable}'`);

// returns "Variable myFirstName with value 'John'"