Get the name of a variable (like nameof operator in C#) [duplicate]

This is my own answer in Q&A style which comes with a bit of a compromise. The trick is here to pass the parameter to the function nameof inside an object by enclosing it in curly braces, like this nameof({myVariable}) instead of nameof(myVariable).

Following this convention, the solution can look like this:

var HD = HD || {};
HD.nameof = function (obj) {
  return Object.keys(obj)[0];
}

And this is how I use it to get the name of the variable/object plus the object’s content/the variable’s value:

const s = HD.nameof({myVariable}) + ': ' + JSON.stringify(myVariable);   

Thus, s will contain the result as requested in the question above.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)