[javascript] Variable name as a string in Javascript

Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)

I would like to do like this:

var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);

--> myFirstName:John

UPDATE

I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:

FooClass = function(){};
FooClass.someMethod = function(json) {
  // Do something
}

instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();

...

From another program:

evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");

In PHP: How to get a variable name as a string in PHP?

This question is related to javascript

The answer is


This works for basic expressions

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

Example

nameof(() => options.displaySize);

Snippet:

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


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

However, I think you should do like "karim79"


You can use the following solution to solve your problem:

const myFirstName = 'John'
Object.keys({myFirstName})[0]

// returns "myFirstName"

var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];

This isn't able to be made into a function as it returns the name of the function's variable.

// THIS DOESN'T WORK
function getVarName(v) {
    return Object.keys({v})[0];
}
// Returns "v"

Edit: Thanks to @Madeo for pointing out how to make this into a function.

function debugVar(varObj) {
    var varName = Object.keys(varObj)[0];
    console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}

You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.


No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").


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/


This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:

_x000D_
_x000D_
   _x000D_
var myFirstName = "Danilo";_x000D_
var varName = Object.keys({myFirstName:0})[0];_x000D_
console.log(varName);
_x000D_
_x000D_
_x000D_

Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys


I've created this function based on JSON as someone suggested, works fine for my debug needs

_x000D_
_x000D_
function debugVar(varNames){_x000D_
let strX = "";_x000D_
function replacer(key, value){_x000D_
    if (value === undefined){return "undef"}_x000D_
    return value_x000D_
    }    _x000D_
for (let arg of arguments){_x000D_
let lastChar;_x000D_
    if (typeof arg!== "string"){_x000D_
        let _arg = JSON.stringify(arg, replacer);_x000D_
        _arg = _arg.replace('{',"");_x000D_
        _arg = _arg.replace('}',"");            _x000D_
        _arg = _arg.replace(/:/g,"=");_x000D_
        _arg = _arg.replace(/"/g,"");_x000D_
        strX+=_arg;_x000D_
    }else{_x000D_
    strX+=arg;_x000D_
    lastChar = arg[arg.length-1];_x000D_
    }_x000D_
    if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};_x000D_
}_x000D_
console.log(strX)    _x000D_
}_x000D_
let a = 42, b = 3, c;_x000D_
debugVar("Begin:",{a,b,c},"end")
_x000D_
_x000D_
_x000D_


When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.

Run in jsfiddle

var jack = 'jill';
function window_getVarName(what)
{
  for (var name in window)
  {
    if (window[name]==what)
    return(name);
  }
  return("");
}
document.write(window_getVarName(jack));

Will write to the window 'jack'.


Shortest way I have found so far to get the variables name as a string:

_x000D_
_x000D_
const name = obj => Object.keys(obj)[0];

const whatsMyName = "Snoop Doggy Dogg";

console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
_x000D_
_x000D_
_x000D_


I needed this, don't want to use objects, and came up with the following solution, turning the question around.

Instead of converting the variable name into a string, I convert a string into a variable.

This only works if the variable name is known of course.

Take this:

var height = 120;
testAlert(height);

This should display:

height: 120

This can be done like this:

function testAlert(ta)
{
    a = window[ta];
    alert(ta + ': ' + a); 
}

var height = 120;
testAlert("height");
// displays: height: 120

So I use the string "height" and turn that into a variable height using the window[] command.


Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.

Here is an example:

_x000D_
_x000D_
// Get John’s properties (firstName, lastName)_x000D_
var john = {firstName: 'John', lastName: 'Doe'};_x000D_
var properties = Object.keys(john);_x000D_
_x000D_
// Show John’s properties_x000D_
var message = 'John’s properties are: ' + properties.join(', ');_x000D_
document.write(message);
_x000D_
_x000D_
_x000D_


best way using Object.keys();

example for getting multi variables names in global scope

// multi varibles for testing
var x = 5 , b = true , m = 6 , v = "str";

// pass all varibles you want in object
function getVarsNames(v = {}){
    // getting keys or names !
    let names = Object.keys(v);
    // return array has real names of varibles 
    return names;
}

//testing if that work or not 
let VarsNames = getVarsNames({x , b , m , v});

console.log(VarsNames); // output is array [x , b , m , v]

You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.


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'"

Like Seth's answer, but uses Object.keys() instead:

_x000D_
_x000D_
const varToString = varObj => Object.keys(varObj)[0]_x000D_
_x000D_
const someVar = 42_x000D_
const displayName = varToString({ someVar })_x000D_
console.log(displayName)
_x000D_
_x000D_
_x000D_