Determine original name of variable after its passed to a function












23















I've got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don't know how to explain it any better than that, so see if this example makes sense.



function getVariableName(unknownVariable){
return unknownVariable.originalName;
}

getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";


This is for a jquery plugin i'm working on, and i would like to be able to display the name of the variable which is passed to a "debug" function.










share|improve this question


















  • 1





    I am not sure what is the purpose of this, since you would need to get interested in variable values than the variable name.

    – Sachin Shanbhag
    Aug 4 '10 at 9:09






  • 2





    There are no variable names when a program is running. No "current" ones, and no "original" ones.

    – Tomalak
    Aug 4 '10 at 9:18






  • 1





    Haha, I figured this was a longshot, but worth a shot nonetheless. There isn't too much purpose, but if you want context you can see the current version of the plugin: andygroff.com/jquery-debugger-debugging-plugin If you view the object example, I would prefer that the title says "clothingCompany Properties" instead of simply "Object Properties" Its not terribly important, but would be nice.

    – Andy Groff
    Aug 4 '10 at 9:23






  • 2





    Somewhat related feature request: Suggestion to add nameof() to TypeScript compiler. If this ever lands you could do nameof(foo) // returns the string "foo".

    – styfle
    Jan 3 '17 at 18:24











  • I've updated my answer below which gets you really close using ES6. Just add curly brackets.

    – styfle
    Aug 10 '18 at 18:23
















23















I've got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don't know how to explain it any better than that, so see if this example makes sense.



function getVariableName(unknownVariable){
return unknownVariable.originalName;
}

getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";


This is for a jquery plugin i'm working on, and i would like to be able to display the name of the variable which is passed to a "debug" function.










share|improve this question


















  • 1





    I am not sure what is the purpose of this, since you would need to get interested in variable values than the variable name.

    – Sachin Shanbhag
    Aug 4 '10 at 9:09






  • 2





    There are no variable names when a program is running. No "current" ones, and no "original" ones.

    – Tomalak
    Aug 4 '10 at 9:18






  • 1





    Haha, I figured this was a longshot, but worth a shot nonetheless. There isn't too much purpose, but if you want context you can see the current version of the plugin: andygroff.com/jquery-debugger-debugging-plugin If you view the object example, I would prefer that the title says "clothingCompany Properties" instead of simply "Object Properties" Its not terribly important, but would be nice.

    – Andy Groff
    Aug 4 '10 at 9:23






  • 2





    Somewhat related feature request: Suggestion to add nameof() to TypeScript compiler. If this ever lands you could do nameof(foo) // returns the string "foo".

    – styfle
    Jan 3 '17 at 18:24











  • I've updated my answer below which gets you really close using ES6. Just add curly brackets.

    – styfle
    Aug 10 '18 at 18:23














23












23








23


2






I've got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don't know how to explain it any better than that, so see if this example makes sense.



function getVariableName(unknownVariable){
return unknownVariable.originalName;
}

getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";


This is for a jquery plugin i'm working on, and i would like to be able to display the name of the variable which is passed to a "debug" function.










share|improve this question














I've got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don't know how to explain it any better than that, so see if this example makes sense.



function getVariableName(unknownVariable){
return unknownVariable.originalName;
}

getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";


This is for a jquery plugin i'm working on, and i would like to be able to display the name of the variable which is passed to a "debug" function.







javascript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Aug 4 '10 at 9:06









Andy GroffAndy Groff

2,1031423




2,1031423








  • 1





    I am not sure what is the purpose of this, since you would need to get interested in variable values than the variable name.

    – Sachin Shanbhag
    Aug 4 '10 at 9:09






  • 2





    There are no variable names when a program is running. No "current" ones, and no "original" ones.

    – Tomalak
    Aug 4 '10 at 9:18






  • 1





    Haha, I figured this was a longshot, but worth a shot nonetheless. There isn't too much purpose, but if you want context you can see the current version of the plugin: andygroff.com/jquery-debugger-debugging-plugin If you view the object example, I would prefer that the title says "clothingCompany Properties" instead of simply "Object Properties" Its not terribly important, but would be nice.

    – Andy Groff
    Aug 4 '10 at 9:23






  • 2





    Somewhat related feature request: Suggestion to add nameof() to TypeScript compiler. If this ever lands you could do nameof(foo) // returns the string "foo".

    – styfle
    Jan 3 '17 at 18:24











  • I've updated my answer below which gets you really close using ES6. Just add curly brackets.

    – styfle
    Aug 10 '18 at 18:23














  • 1





    I am not sure what is the purpose of this, since you would need to get interested in variable values than the variable name.

    – Sachin Shanbhag
    Aug 4 '10 at 9:09






  • 2





    There are no variable names when a program is running. No "current" ones, and no "original" ones.

    – Tomalak
    Aug 4 '10 at 9:18






  • 1





    Haha, I figured this was a longshot, but worth a shot nonetheless. There isn't too much purpose, but if you want context you can see the current version of the plugin: andygroff.com/jquery-debugger-debugging-plugin If you view the object example, I would prefer that the title says "clothingCompany Properties" instead of simply "Object Properties" Its not terribly important, but would be nice.

    – Andy Groff
    Aug 4 '10 at 9:23






  • 2





    Somewhat related feature request: Suggestion to add nameof() to TypeScript compiler. If this ever lands you could do nameof(foo) // returns the string "foo".

    – styfle
    Jan 3 '17 at 18:24











  • I've updated my answer below which gets you really close using ES6. Just add curly brackets.

    – styfle
    Aug 10 '18 at 18:23








1




1





I am not sure what is the purpose of this, since you would need to get interested in variable values than the variable name.

– Sachin Shanbhag
Aug 4 '10 at 9:09





I am not sure what is the purpose of this, since you would need to get interested in variable values than the variable name.

– Sachin Shanbhag
Aug 4 '10 at 9:09




2




2





There are no variable names when a program is running. No "current" ones, and no "original" ones.

– Tomalak
Aug 4 '10 at 9:18





There are no variable names when a program is running. No "current" ones, and no "original" ones.

– Tomalak
Aug 4 '10 at 9:18




1




1





Haha, I figured this was a longshot, but worth a shot nonetheless. There isn't too much purpose, but if you want context you can see the current version of the plugin: andygroff.com/jquery-debugger-debugging-plugin If you view the object example, I would prefer that the title says "clothingCompany Properties" instead of simply "Object Properties" Its not terribly important, but would be nice.

– Andy Groff
Aug 4 '10 at 9:23





Haha, I figured this was a longshot, but worth a shot nonetheless. There isn't too much purpose, but if you want context you can see the current version of the plugin: andygroff.com/jquery-debugger-debugging-plugin If you view the object example, I would prefer that the title says "clothingCompany Properties" instead of simply "Object Properties" Its not terribly important, but would be nice.

– Andy Groff
Aug 4 '10 at 9:23




2




2





Somewhat related feature request: Suggestion to add nameof() to TypeScript compiler. If this ever lands you could do nameof(foo) // returns the string "foo".

– styfle
Jan 3 '17 at 18:24





Somewhat related feature request: Suggestion to add nameof() to TypeScript compiler. If this ever lands you could do nameof(foo) // returns the string "foo".

– styfle
Jan 3 '17 at 18:24













I've updated my answer below which gets you really close using ES6. Just add curly brackets.

– styfle
Aug 10 '18 at 18:23





I've updated my answer below which gets you really close using ES6. Just add curly brackets.

– styfle
Aug 10 '18 at 18:23












6 Answers
6






active

oldest

votes


















19














You're right, this is very much impossible in any sane way, since only the value gets passed into the function.






share|improve this answer





















  • 7





    what's the insane way?

    – johny why
    Jan 14 '16 at 18:01






  • 11





    Get a backtrace, get the file and line number of the function invocation, load the source code of that file, find and parse that line, try to figure out which variable was your parameter. Since there may be any number of function calls on one line and functions may be aliased at runtime, not to mention the complexity of the task, I hope the insanity of this is self evident.

    – deceze
    Jan 14 '16 at 19:32











  • This is now somewhat possible, see my answer.

    – Offirmo
    Sep 15 '17 at 1:29



















3














This is now somehow possible thanks to ES6:






function getVariableName(unknownVariableInAHash){
return Object.keys(unknownVariableInAHash)[0]
}

const foo = 42
const bar = 'baz'
console.log(getVariableName({foo})) //returns string "foo"
console.log(getVariableName({bar})) //returns string "bar"





The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.






share|improve this answer



















  • 2





    {foo} is just {foo:42}... so you're just sending it as an object. See New notations in ECMAScript 2015: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Cody G.
    Sep 28 '17 at 18:23













  • @CodyG. I'm perfectly aware of that.

    – Offirmo
    Sep 28 '17 at 22:17






  • 5





    Then you shouldn't say "somehow possible thanks to es6", your answer is basically --- 'you can do this by sending the value as an object with the key as the variable name'... which is also easily done in es5 with a polyfill of Object.keys, or simply by passing an object with the variable name as another property.

    – Cody G.
    Sep 28 '17 at 22:42





















1














Well, all the global variables are properties of global object (this or window), aren't they?
So when I wanted to find out the name of my variables, I made following function:



var getName = function(variable) {
for (var prop in window) {
if (variable === window[prop]) {
return prop;
}
}
}
var helloWorld = "Hello World!";
console.log(getName(helloWorld)); // "helloWorld"


Sometimes doesn't work, for example, if 2 strings are created without new operator and have the same value.






share|improve this answer


























  • Does this depend on being run in the browser? Or am I misunderstanding what window is?

    – byxor
    Jun 26 '17 at 16:26






  • 1





    This won't work if two objects have the same value. window.a=1;window.b=1; It will return the name of the first matching value. Additionally, it is bad practice to define variables in the global scope.

    – styfle
    Jun 26 '17 at 17:10



















1














Global w/string method



Here is a technique that you can use to keep the name and the value of the variable.






// Set up a global variable called g
var g = {};
// All other variables should be defined as properties of this global object
g.foo = 'hello';
g.bar = 'world';

// Setup function
function doStuff(str) {
if (str in g) {
var name = str;
var value = g[str];
// Do stuff with the variable name and the variable value here
// For this example, simply print to console
console.log(name, value);
} else {
console.error('Oh snap! That variable does not exist!');
}
}

// Call the function
doStuff('foo'); // log: foo hello
doStuff('bar'); // log: bar world
doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!





This is effectively creating a dictionary that maps variable names to their value. This probably won't work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.



ES6 object method



In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.






function getVariableName(unknownVariable) {
return Object.keys(unknownVariable)[0];
}

var foo = 'hello';
var output = getVariableName({ foo }); // Note the curly brackets
console.log(output);





This works because you created a new object with key foo and value the same as the variable foo, in this case hello. Then our helper method gets the first key as a string.



Credit goes to this tweet.






share|improve this answer


























  • Thanks for the answer. This is a nice solution, although it really doesn't solve the problem I had. I was writing a debugging plugin which was going to create a modal alert with information on variables, including its name. It would need to run with any javascript, so storing all variables as object properties isn't a viable solution. Thanks!

    – Andy Groff
    Oct 20 '13 at 11:15











  • @AndyGroff substituting the g variable for the window variable might solve your problem. But ultimately you will have to access the variables by string instead of the identifier.

    – styfle
    Oct 21 '13 at 17:09



















0














Converting a set of unique variable into one JSON object for which I wrote this function



function makeJSON(){ //Pass the variable names as string parameters [not by reference]
ret={};
for(i=0; i<arguments.length; i++){
eval("ret."+arguments[i]+"="+arguments[i]);
}
return ret;
}


Example:



a=b=c=3;
console.log(makeJSON('a','b','c'));


Perhaps this is the reason for this query






share|improve this answer





















  • 5





    ret[x] = x; absolutely no reason for eval here!

    – deceze
    Apr 29 '16 at 23:14



















0














As you want debugging (show name of var and value of var),
I've been looking for it too, and just want to share my finding.



It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.



It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :



foo = 'bar';

debug('foo');

function debug(Variable) {
var Value = this[Variable]; // in that occurrence, it is equivalent to
// this['foo'] which is the syntax to call the global variable foo
console.log(Variable + " is " + Value); // print "foo is bar"
}





share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3404057%2fdetermine-original-name-of-variable-after-its-passed-to-a-function%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    6 Answers
    6






    active

    oldest

    votes








    6 Answers
    6






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    19














    You're right, this is very much impossible in any sane way, since only the value gets passed into the function.






    share|improve this answer





















    • 7





      what's the insane way?

      – johny why
      Jan 14 '16 at 18:01






    • 11





      Get a backtrace, get the file and line number of the function invocation, load the source code of that file, find and parse that line, try to figure out which variable was your parameter. Since there may be any number of function calls on one line and functions may be aliased at runtime, not to mention the complexity of the task, I hope the insanity of this is self evident.

      – deceze
      Jan 14 '16 at 19:32











    • This is now somewhat possible, see my answer.

      – Offirmo
      Sep 15 '17 at 1:29
















    19














    You're right, this is very much impossible in any sane way, since only the value gets passed into the function.






    share|improve this answer





















    • 7





      what's the insane way?

      – johny why
      Jan 14 '16 at 18:01






    • 11





      Get a backtrace, get the file and line number of the function invocation, load the source code of that file, find and parse that line, try to figure out which variable was your parameter. Since there may be any number of function calls on one line and functions may be aliased at runtime, not to mention the complexity of the task, I hope the insanity of this is self evident.

      – deceze
      Jan 14 '16 at 19:32











    • This is now somewhat possible, see my answer.

      – Offirmo
      Sep 15 '17 at 1:29














    19












    19








    19







    You're right, this is very much impossible in any sane way, since only the value gets passed into the function.






    share|improve this answer















    You're right, this is very much impossible in any sane way, since only the value gets passed into the function.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jun 24 '15 at 11:16









    Andrei V

    5,50443452




    5,50443452










    answered Aug 4 '10 at 9:08









    decezedeceze

    400k64546703




    400k64546703








    • 7





      what's the insane way?

      – johny why
      Jan 14 '16 at 18:01






    • 11





      Get a backtrace, get the file and line number of the function invocation, load the source code of that file, find and parse that line, try to figure out which variable was your parameter. Since there may be any number of function calls on one line and functions may be aliased at runtime, not to mention the complexity of the task, I hope the insanity of this is self evident.

      – deceze
      Jan 14 '16 at 19:32











    • This is now somewhat possible, see my answer.

      – Offirmo
      Sep 15 '17 at 1:29














    • 7





      what's the insane way?

      – johny why
      Jan 14 '16 at 18:01






    • 11





      Get a backtrace, get the file and line number of the function invocation, load the source code of that file, find and parse that line, try to figure out which variable was your parameter. Since there may be any number of function calls on one line and functions may be aliased at runtime, not to mention the complexity of the task, I hope the insanity of this is self evident.

      – deceze
      Jan 14 '16 at 19:32











    • This is now somewhat possible, see my answer.

      – Offirmo
      Sep 15 '17 at 1:29








    7




    7





    what's the insane way?

    – johny why
    Jan 14 '16 at 18:01





    what's the insane way?

    – johny why
    Jan 14 '16 at 18:01




    11




    11





    Get a backtrace, get the file and line number of the function invocation, load the source code of that file, find and parse that line, try to figure out which variable was your parameter. Since there may be any number of function calls on one line and functions may be aliased at runtime, not to mention the complexity of the task, I hope the insanity of this is self evident.

    – deceze
    Jan 14 '16 at 19:32





    Get a backtrace, get the file and line number of the function invocation, load the source code of that file, find and parse that line, try to figure out which variable was your parameter. Since there may be any number of function calls on one line and functions may be aliased at runtime, not to mention the complexity of the task, I hope the insanity of this is self evident.

    – deceze
    Jan 14 '16 at 19:32













    This is now somewhat possible, see my answer.

    – Offirmo
    Sep 15 '17 at 1:29





    This is now somewhat possible, see my answer.

    – Offirmo
    Sep 15 '17 at 1:29













    3














    This is now somehow possible thanks to ES6:






    function getVariableName(unknownVariableInAHash){
    return Object.keys(unknownVariableInAHash)[0]
    }

    const foo = 42
    const bar = 'baz'
    console.log(getVariableName({foo})) //returns string "foo"
    console.log(getVariableName({bar})) //returns string "bar"





    The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.






    share|improve this answer



















    • 2





      {foo} is just {foo:42}... so you're just sending it as an object. See New notations in ECMAScript 2015: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

      – Cody G.
      Sep 28 '17 at 18:23













    • @CodyG. I'm perfectly aware of that.

      – Offirmo
      Sep 28 '17 at 22:17






    • 5





      Then you shouldn't say "somehow possible thanks to es6", your answer is basically --- 'you can do this by sending the value as an object with the key as the variable name'... which is also easily done in es5 with a polyfill of Object.keys, or simply by passing an object with the variable name as another property.

      – Cody G.
      Sep 28 '17 at 22:42


















    3














    This is now somehow possible thanks to ES6:






    function getVariableName(unknownVariableInAHash){
    return Object.keys(unknownVariableInAHash)[0]
    }

    const foo = 42
    const bar = 'baz'
    console.log(getVariableName({foo})) //returns string "foo"
    console.log(getVariableName({bar})) //returns string "bar"





    The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.






    share|improve this answer



















    • 2





      {foo} is just {foo:42}... so you're just sending it as an object. See New notations in ECMAScript 2015: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

      – Cody G.
      Sep 28 '17 at 18:23













    • @CodyG. I'm perfectly aware of that.

      – Offirmo
      Sep 28 '17 at 22:17






    • 5





      Then you shouldn't say "somehow possible thanks to es6", your answer is basically --- 'you can do this by sending the value as an object with the key as the variable name'... which is also easily done in es5 with a polyfill of Object.keys, or simply by passing an object with the variable name as another property.

      – Cody G.
      Sep 28 '17 at 22:42
















    3












    3








    3







    This is now somehow possible thanks to ES6:






    function getVariableName(unknownVariableInAHash){
    return Object.keys(unknownVariableInAHash)[0]
    }

    const foo = 42
    const bar = 'baz'
    console.log(getVariableName({foo})) //returns string "foo"
    console.log(getVariableName({bar})) //returns string "bar"





    The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.






    share|improve this answer













    This is now somehow possible thanks to ES6:






    function getVariableName(unknownVariableInAHash){
    return Object.keys(unknownVariableInAHash)[0]
    }

    const foo = 42
    const bar = 'baz'
    console.log(getVariableName({foo})) //returns string "foo"
    console.log(getVariableName({bar})) //returns string "bar"





    The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.






    function getVariableName(unknownVariableInAHash){
    return Object.keys(unknownVariableInAHash)[0]
    }

    const foo = 42
    const bar = 'baz'
    console.log(getVariableName({foo})) //returns string "foo"
    console.log(getVariableName({bar})) //returns string "bar"





    function getVariableName(unknownVariableInAHash){
    return Object.keys(unknownVariableInAHash)[0]
    }

    const foo = 42
    const bar = 'baz'
    console.log(getVariableName({foo})) //returns string "foo"
    console.log(getVariableName({bar})) //returns string "bar"






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Sep 15 '17 at 1:28









    OffirmoOffirmo

    10.5k55182




    10.5k55182








    • 2





      {foo} is just {foo:42}... so you're just sending it as an object. See New notations in ECMAScript 2015: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

      – Cody G.
      Sep 28 '17 at 18:23













    • @CodyG. I'm perfectly aware of that.

      – Offirmo
      Sep 28 '17 at 22:17






    • 5





      Then you shouldn't say "somehow possible thanks to es6", your answer is basically --- 'you can do this by sending the value as an object with the key as the variable name'... which is also easily done in es5 with a polyfill of Object.keys, or simply by passing an object with the variable name as another property.

      – Cody G.
      Sep 28 '17 at 22:42
















    • 2





      {foo} is just {foo:42}... so you're just sending it as an object. See New notations in ECMAScript 2015: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

      – Cody G.
      Sep 28 '17 at 18:23













    • @CodyG. I'm perfectly aware of that.

      – Offirmo
      Sep 28 '17 at 22:17






    • 5





      Then you shouldn't say "somehow possible thanks to es6", your answer is basically --- 'you can do this by sending the value as an object with the key as the variable name'... which is also easily done in es5 with a polyfill of Object.keys, or simply by passing an object with the variable name as another property.

      – Cody G.
      Sep 28 '17 at 22:42










    2




    2





    {foo} is just {foo:42}... so you're just sending it as an object. See New notations in ECMAScript 2015: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Cody G.
    Sep 28 '17 at 18:23







    {foo} is just {foo:42}... so you're just sending it as an object. See New notations in ECMAScript 2015: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Cody G.
    Sep 28 '17 at 18:23















    @CodyG. I'm perfectly aware of that.

    – Offirmo
    Sep 28 '17 at 22:17





    @CodyG. I'm perfectly aware of that.

    – Offirmo
    Sep 28 '17 at 22:17




    5




    5





    Then you shouldn't say "somehow possible thanks to es6", your answer is basically --- 'you can do this by sending the value as an object with the key as the variable name'... which is also easily done in es5 with a polyfill of Object.keys, or simply by passing an object with the variable name as another property.

    – Cody G.
    Sep 28 '17 at 22:42







    Then you shouldn't say "somehow possible thanks to es6", your answer is basically --- 'you can do this by sending the value as an object with the key as the variable name'... which is also easily done in es5 with a polyfill of Object.keys, or simply by passing an object with the variable name as another property.

    – Cody G.
    Sep 28 '17 at 22:42













    1














    Well, all the global variables are properties of global object (this or window), aren't they?
    So when I wanted to find out the name of my variables, I made following function:



    var getName = function(variable) {
    for (var prop in window) {
    if (variable === window[prop]) {
    return prop;
    }
    }
    }
    var helloWorld = "Hello World!";
    console.log(getName(helloWorld)); // "helloWorld"


    Sometimes doesn't work, for example, if 2 strings are created without new operator and have the same value.






    share|improve this answer


























    • Does this depend on being run in the browser? Or am I misunderstanding what window is?

      – byxor
      Jun 26 '17 at 16:26






    • 1





      This won't work if two objects have the same value. window.a=1;window.b=1; It will return the name of the first matching value. Additionally, it is bad practice to define variables in the global scope.

      – styfle
      Jun 26 '17 at 17:10
















    1














    Well, all the global variables are properties of global object (this or window), aren't they?
    So when I wanted to find out the name of my variables, I made following function:



    var getName = function(variable) {
    for (var prop in window) {
    if (variable === window[prop]) {
    return prop;
    }
    }
    }
    var helloWorld = "Hello World!";
    console.log(getName(helloWorld)); // "helloWorld"


    Sometimes doesn't work, for example, if 2 strings are created without new operator and have the same value.






    share|improve this answer


























    • Does this depend on being run in the browser? Or am I misunderstanding what window is?

      – byxor
      Jun 26 '17 at 16:26






    • 1





      This won't work if two objects have the same value. window.a=1;window.b=1; It will return the name of the first matching value. Additionally, it is bad practice to define variables in the global scope.

      – styfle
      Jun 26 '17 at 17:10














    1












    1








    1







    Well, all the global variables are properties of global object (this or window), aren't they?
    So when I wanted to find out the name of my variables, I made following function:



    var getName = function(variable) {
    for (var prop in window) {
    if (variable === window[prop]) {
    return prop;
    }
    }
    }
    var helloWorld = "Hello World!";
    console.log(getName(helloWorld)); // "helloWorld"


    Sometimes doesn't work, for example, if 2 strings are created without new operator and have the same value.






    share|improve this answer















    Well, all the global variables are properties of global object (this or window), aren't they?
    So when I wanted to find out the name of my variables, I made following function:



    var getName = function(variable) {
    for (var prop in window) {
    if (variable === window[prop]) {
    return prop;
    }
    }
    }
    var helloWorld = "Hello World!";
    console.log(getName(helloWorld)); // "helloWorld"


    Sometimes doesn't work, for example, if 2 strings are created without new operator and have the same value.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jul 18 '15 at 12:57

























    answered Jun 7 '14 at 19:37









    RunninglVlanRunninglVlan

    11118




    11118













    • Does this depend on being run in the browser? Or am I misunderstanding what window is?

      – byxor
      Jun 26 '17 at 16:26






    • 1





      This won't work if two objects have the same value. window.a=1;window.b=1; It will return the name of the first matching value. Additionally, it is bad practice to define variables in the global scope.

      – styfle
      Jun 26 '17 at 17:10



















    • Does this depend on being run in the browser? Or am I misunderstanding what window is?

      – byxor
      Jun 26 '17 at 16:26






    • 1





      This won't work if two objects have the same value. window.a=1;window.b=1; It will return the name of the first matching value. Additionally, it is bad practice to define variables in the global scope.

      – styfle
      Jun 26 '17 at 17:10

















    Does this depend on being run in the browser? Or am I misunderstanding what window is?

    – byxor
    Jun 26 '17 at 16:26





    Does this depend on being run in the browser? Or am I misunderstanding what window is?

    – byxor
    Jun 26 '17 at 16:26




    1




    1





    This won't work if two objects have the same value. window.a=1;window.b=1; It will return the name of the first matching value. Additionally, it is bad practice to define variables in the global scope.

    – styfle
    Jun 26 '17 at 17:10





    This won't work if two objects have the same value. window.a=1;window.b=1; It will return the name of the first matching value. Additionally, it is bad practice to define variables in the global scope.

    – styfle
    Jun 26 '17 at 17:10











    1














    Global w/string method



    Here is a technique that you can use to keep the name and the value of the variable.






    // Set up a global variable called g
    var g = {};
    // All other variables should be defined as properties of this global object
    g.foo = 'hello';
    g.bar = 'world';

    // Setup function
    function doStuff(str) {
    if (str in g) {
    var name = str;
    var value = g[str];
    // Do stuff with the variable name and the variable value here
    // For this example, simply print to console
    console.log(name, value);
    } else {
    console.error('Oh snap! That variable does not exist!');
    }
    }

    // Call the function
    doStuff('foo'); // log: foo hello
    doStuff('bar'); // log: bar world
    doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!





    This is effectively creating a dictionary that maps variable names to their value. This probably won't work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.



    ES6 object method



    In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.






    function getVariableName(unknownVariable) {
    return Object.keys(unknownVariable)[0];
    }

    var foo = 'hello';
    var output = getVariableName({ foo }); // Note the curly brackets
    console.log(output);





    This works because you created a new object with key foo and value the same as the variable foo, in this case hello. Then our helper method gets the first key as a string.



    Credit goes to this tweet.






    share|improve this answer


























    • Thanks for the answer. This is a nice solution, although it really doesn't solve the problem I had. I was writing a debugging plugin which was going to create a modal alert with information on variables, including its name. It would need to run with any javascript, so storing all variables as object properties isn't a viable solution. Thanks!

      – Andy Groff
      Oct 20 '13 at 11:15











    • @AndyGroff substituting the g variable for the window variable might solve your problem. But ultimately you will have to access the variables by string instead of the identifier.

      – styfle
      Oct 21 '13 at 17:09
















    1














    Global w/string method



    Here is a technique that you can use to keep the name and the value of the variable.






    // Set up a global variable called g
    var g = {};
    // All other variables should be defined as properties of this global object
    g.foo = 'hello';
    g.bar = 'world';

    // Setup function
    function doStuff(str) {
    if (str in g) {
    var name = str;
    var value = g[str];
    // Do stuff with the variable name and the variable value here
    // For this example, simply print to console
    console.log(name, value);
    } else {
    console.error('Oh snap! That variable does not exist!');
    }
    }

    // Call the function
    doStuff('foo'); // log: foo hello
    doStuff('bar'); // log: bar world
    doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!





    This is effectively creating a dictionary that maps variable names to their value. This probably won't work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.



    ES6 object method



    In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.






    function getVariableName(unknownVariable) {
    return Object.keys(unknownVariable)[0];
    }

    var foo = 'hello';
    var output = getVariableName({ foo }); // Note the curly brackets
    console.log(output);





    This works because you created a new object with key foo and value the same as the variable foo, in this case hello. Then our helper method gets the first key as a string.



    Credit goes to this tweet.






    share|improve this answer


























    • Thanks for the answer. This is a nice solution, although it really doesn't solve the problem I had. I was writing a debugging plugin which was going to create a modal alert with information on variables, including its name. It would need to run with any javascript, so storing all variables as object properties isn't a viable solution. Thanks!

      – Andy Groff
      Oct 20 '13 at 11:15











    • @AndyGroff substituting the g variable for the window variable might solve your problem. But ultimately you will have to access the variables by string instead of the identifier.

      – styfle
      Oct 21 '13 at 17:09














    1












    1








    1







    Global w/string method



    Here is a technique that you can use to keep the name and the value of the variable.






    // Set up a global variable called g
    var g = {};
    // All other variables should be defined as properties of this global object
    g.foo = 'hello';
    g.bar = 'world';

    // Setup function
    function doStuff(str) {
    if (str in g) {
    var name = str;
    var value = g[str];
    // Do stuff with the variable name and the variable value here
    // For this example, simply print to console
    console.log(name, value);
    } else {
    console.error('Oh snap! That variable does not exist!');
    }
    }

    // Call the function
    doStuff('foo'); // log: foo hello
    doStuff('bar'); // log: bar world
    doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!





    This is effectively creating a dictionary that maps variable names to their value. This probably won't work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.



    ES6 object method



    In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.






    function getVariableName(unknownVariable) {
    return Object.keys(unknownVariable)[0];
    }

    var foo = 'hello';
    var output = getVariableName({ foo }); // Note the curly brackets
    console.log(output);





    This works because you created a new object with key foo and value the same as the variable foo, in this case hello. Then our helper method gets the first key as a string.



    Credit goes to this tweet.






    share|improve this answer















    Global w/string method



    Here is a technique that you can use to keep the name and the value of the variable.






    // Set up a global variable called g
    var g = {};
    // All other variables should be defined as properties of this global object
    g.foo = 'hello';
    g.bar = 'world';

    // Setup function
    function doStuff(str) {
    if (str in g) {
    var name = str;
    var value = g[str];
    // Do stuff with the variable name and the variable value here
    // For this example, simply print to console
    console.log(name, value);
    } else {
    console.error('Oh snap! That variable does not exist!');
    }
    }

    // Call the function
    doStuff('foo'); // log: foo hello
    doStuff('bar'); // log: bar world
    doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!





    This is effectively creating a dictionary that maps variable names to their value. This probably won't work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.



    ES6 object method



    In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.






    function getVariableName(unknownVariable) {
    return Object.keys(unknownVariable)[0];
    }

    var foo = 'hello';
    var output = getVariableName({ foo }); // Note the curly brackets
    console.log(output);





    This works because you created a new object with key foo and value the same as the variable foo, in this case hello. Then our helper method gets the first key as a string.



    Credit goes to this tweet.






    // Set up a global variable called g
    var g = {};
    // All other variables should be defined as properties of this global object
    g.foo = 'hello';
    g.bar = 'world';

    // Setup function
    function doStuff(str) {
    if (str in g) {
    var name = str;
    var value = g[str];
    // Do stuff with the variable name and the variable value here
    // For this example, simply print to console
    console.log(name, value);
    } else {
    console.error('Oh snap! That variable does not exist!');
    }
    }

    // Call the function
    doStuff('foo'); // log: foo hello
    doStuff('bar'); // log: bar world
    doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!





    // Set up a global variable called g
    var g = {};
    // All other variables should be defined as properties of this global object
    g.foo = 'hello';
    g.bar = 'world';

    // Setup function
    function doStuff(str) {
    if (str in g) {
    var name = str;
    var value = g[str];
    // Do stuff with the variable name and the variable value here
    // For this example, simply print to console
    console.log(name, value);
    } else {
    console.error('Oh snap! That variable does not exist!');
    }
    }

    // Call the function
    doStuff('foo'); // log: foo hello
    doStuff('bar'); // log: bar world
    doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!





    function getVariableName(unknownVariable) {
    return Object.keys(unknownVariable)[0];
    }

    var foo = 'hello';
    var output = getVariableName({ foo }); // Note the curly brackets
    console.log(output);





    function getVariableName(unknownVariable) {
    return Object.keys(unknownVariable)[0];
    }

    var foo = 'hello';
    var output = getVariableName({ foo }); // Note the curly brackets
    console.log(output);






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Aug 10 '18 at 17:57

























    answered Oct 12 '13 at 1:12









    styflestyfle

    6,978155294




    6,978155294













    • Thanks for the answer. This is a nice solution, although it really doesn't solve the problem I had. I was writing a debugging plugin which was going to create a modal alert with information on variables, including its name. It would need to run with any javascript, so storing all variables as object properties isn't a viable solution. Thanks!

      – Andy Groff
      Oct 20 '13 at 11:15











    • @AndyGroff substituting the g variable for the window variable might solve your problem. But ultimately you will have to access the variables by string instead of the identifier.

      – styfle
      Oct 21 '13 at 17:09



















    • Thanks for the answer. This is a nice solution, although it really doesn't solve the problem I had. I was writing a debugging plugin which was going to create a modal alert with information on variables, including its name. It would need to run with any javascript, so storing all variables as object properties isn't a viable solution. Thanks!

      – Andy Groff
      Oct 20 '13 at 11:15











    • @AndyGroff substituting the g variable for the window variable might solve your problem. But ultimately you will have to access the variables by string instead of the identifier.

      – styfle
      Oct 21 '13 at 17:09

















    Thanks for the answer. This is a nice solution, although it really doesn't solve the problem I had. I was writing a debugging plugin which was going to create a modal alert with information on variables, including its name. It would need to run with any javascript, so storing all variables as object properties isn't a viable solution. Thanks!

    – Andy Groff
    Oct 20 '13 at 11:15





    Thanks for the answer. This is a nice solution, although it really doesn't solve the problem I had. I was writing a debugging plugin which was going to create a modal alert with information on variables, including its name. It would need to run with any javascript, so storing all variables as object properties isn't a viable solution. Thanks!

    – Andy Groff
    Oct 20 '13 at 11:15













    @AndyGroff substituting the g variable for the window variable might solve your problem. But ultimately you will have to access the variables by string instead of the identifier.

    – styfle
    Oct 21 '13 at 17:09





    @AndyGroff substituting the g variable for the window variable might solve your problem. But ultimately you will have to access the variables by string instead of the identifier.

    – styfle
    Oct 21 '13 at 17:09











    0














    Converting a set of unique variable into one JSON object for which I wrote this function



    function makeJSON(){ //Pass the variable names as string parameters [not by reference]
    ret={};
    for(i=0; i<arguments.length; i++){
    eval("ret."+arguments[i]+"="+arguments[i]);
    }
    return ret;
    }


    Example:



    a=b=c=3;
    console.log(makeJSON('a','b','c'));


    Perhaps this is the reason for this query






    share|improve this answer





















    • 5





      ret[x] = x; absolutely no reason for eval here!

      – deceze
      Apr 29 '16 at 23:14
















    0














    Converting a set of unique variable into one JSON object for which I wrote this function



    function makeJSON(){ //Pass the variable names as string parameters [not by reference]
    ret={};
    for(i=0; i<arguments.length; i++){
    eval("ret."+arguments[i]+"="+arguments[i]);
    }
    return ret;
    }


    Example:



    a=b=c=3;
    console.log(makeJSON('a','b','c'));


    Perhaps this is the reason for this query






    share|improve this answer





















    • 5





      ret[x] = x; absolutely no reason for eval here!

      – deceze
      Apr 29 '16 at 23:14














    0












    0








    0







    Converting a set of unique variable into one JSON object for which I wrote this function



    function makeJSON(){ //Pass the variable names as string parameters [not by reference]
    ret={};
    for(i=0; i<arguments.length; i++){
    eval("ret."+arguments[i]+"="+arguments[i]);
    }
    return ret;
    }


    Example:



    a=b=c=3;
    console.log(makeJSON('a','b','c'));


    Perhaps this is the reason for this query






    share|improve this answer















    Converting a set of unique variable into one JSON object for which I wrote this function



    function makeJSON(){ //Pass the variable names as string parameters [not by reference]
    ret={};
    for(i=0; i<arguments.length; i++){
    eval("ret."+arguments[i]+"="+arguments[i]);
    }
    return ret;
    }


    Example:



    a=b=c=3;
    console.log(makeJSON('a','b','c'));


    Perhaps this is the reason for this query







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Dec 22 '15 at 14:08

























    answered Dec 17 '15 at 2:52









    JudeJude

    294




    294








    • 5





      ret[x] = x; absolutely no reason for eval here!

      – deceze
      Apr 29 '16 at 23:14














    • 5





      ret[x] = x; absolutely no reason for eval here!

      – deceze
      Apr 29 '16 at 23:14








    5




    5





    ret[x] = x; absolutely no reason for eval here!

    – deceze
    Apr 29 '16 at 23:14





    ret[x] = x; absolutely no reason for eval here!

    – deceze
    Apr 29 '16 at 23:14











    0














    As you want debugging (show name of var and value of var),
    I've been looking for it too, and just want to share my finding.



    It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.



    It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :



    foo = 'bar';

    debug('foo');

    function debug(Variable) {
    var Value = this[Variable]; // in that occurrence, it is equivalent to
    // this['foo'] which is the syntax to call the global variable foo
    console.log(Variable + " is " + Value); // print "foo is bar"
    }





    share|improve this answer






























      0














      As you want debugging (show name of var and value of var),
      I've been looking for it too, and just want to share my finding.



      It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.



      It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :



      foo = 'bar';

      debug('foo');

      function debug(Variable) {
      var Value = this[Variable]; // in that occurrence, it is equivalent to
      // this['foo'] which is the syntax to call the global variable foo
      console.log(Variable + " is " + Value); // print "foo is bar"
      }





      share|improve this answer




























        0












        0








        0







        As you want debugging (show name of var and value of var),
        I've been looking for it too, and just want to share my finding.



        It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.



        It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :



        foo = 'bar';

        debug('foo');

        function debug(Variable) {
        var Value = this[Variable]; // in that occurrence, it is equivalent to
        // this['foo'] which is the syntax to call the global variable foo
        console.log(Variable + " is " + Value); // print "foo is bar"
        }





        share|improve this answer















        As you want debugging (show name of var and value of var),
        I've been looking for it too, and just want to share my finding.



        It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.



        It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :



        foo = 'bar';

        debug('foo');

        function debug(Variable) {
        var Value = this[Variable]; // in that occurrence, it is equivalent to
        // this['foo'] which is the syntax to call the global variable foo
        console.log(Variable + " is " + Value); // print "foo is bar"
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 3 at 1:04

























        answered Dec 31 '18 at 17:01









        HelworHelwor

        12




        12






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3404057%2fdetermine-original-name-of-variable-after-its-passed-to-a-function%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            SQL update select statement

            WPF add header to Image with URL pettitions [duplicate]