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 =
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]);
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.
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.
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.
This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:
var myFirstName = "Danilo";
var varName = Object.keys({myFirstName:0})[0];
console.log(varName);
Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
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/