LostInCyberSpace
LostInCyberSpace

Reputation: 433

How do I retrieve the name of a variable in JavaScript

Ok so let's say I have an assortment of varables:

tab = document.createOjbect('table');
str = 'asdf';
ary = [123, 456, 789];
obj = {a:123, b:456, c:789};

A Piece of code to 'stringify' them:

function Stringify(){
    var con = this.constructor.name;
    if(con == 'String')             return this;
    if(con == 'Arrray')             return this.toString();
    if(con == 'Object')             return JSON.stringify(this);
    if(con == 'HTMLTableElement')   return this.outerHTML;
}

An array containing the variables:

var aVar = [tab, str, ary, obj];

And I loop the array to 'stringify' its content:

for(var i in aVar){
    console.log(
        Stringify.call( aVar[i] );
    );
}

I get the expected list of stringed objects:

<table></table>
asdf
123,456,789
{"a":123,"b":456,"c":789}

But what if I wanted to include the name of the variables in the logs?:

tab: <table></table>
str: asdf
ary: 123,456,789
obj: {"a":123,"b":456,"c":789}

How would I even go about that?:

for(var i in aVar){
    var id = // get the name of the variable at aVar[i]
    console.log(
        id + ': ',
        Stringify.call( aVar[i] );
    );
}

Upvotes: 0

Views: 98

Answers (1)

Valentin Waeselynck
Valentin Waeselynck

Reputation: 6061

It is not possible, and does not really make sense. You have to understand that functions manipulate values, not variables.

When executing this:

var aVar = [tab, str, ary, obj];

What is put in the array is values, not variables, although it syntactically looks so. The values know nothing about the variables that reference them.

Think about it: a value could be referenced by several variables. What sense would it make to get the access the name of (one of the) variable that has referenced it at some earlier point?

I'm afraid that the only solutions for your use case are to either carry the 'variable name' along your execution flow, or to hardcode your logic for each of the variables.

Upvotes: 1

Related Questions