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 =
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
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);
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'.
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]
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"