Get variable name. javascript “reflection”

Actually you CAN. Here is a snippet:

function getVarName(v) {
    for (var key in window) {
        if (window[key] === v)
            return key;
    }
}
var testvar = 13142;
function test(t) {
    var varName = getVarName(t);
    // window[varName] -- your variable actualy
    alert(varName);
}
test(testvar); // testvar

The other problem is if you create some vars that contain the same variable. Then first var will be returned.

Leave a Comment