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 =
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){
let strX = "";
function replacer(key, value){
if (value === undefined){return "undef"}
return value
}
for (let arg of arguments){
let lastChar;
if (typeof arg!== "string"){
let _arg = JSON.stringify(arg, replacer);
_arg = _arg.replace('{',"");
_arg = _arg.replace('}',"");
_arg = _arg.replace(/:/g,"=");
_arg = _arg.replace(/"/g,"");
strX+=_arg;
}else{
strX+=arg;
lastChar = arg[arg.length-1];
}
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
}
console.log(strX)
}
let a = 42, b = 3, c;
debugVar("Begin:",{a,b,c},"end")
No, there is not.
Besides, if you can write variablesName(myFirstName)
, you already know the variable name ("myFirstName").
Shorts way I have found so far to get the variables name as a string:
const name = obj => Object.keys(obj)[0];
const whatsMyName = "Snoop Doggy Dogg";
console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
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'"
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
// Get John’s properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John’s properties
var message = 'John’s properties are: ' + properties.join(', ');
document.write(message);
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)