1

I have a variable as such:

 var foo = ["cool", "cool"];

How do I get the variable name, foo, as a string? In other words, given foo, how do I get "foo"? I want to use it in the following context where "foo" is used in getElementById(...):

  document.getElementById("foo").innerHTML = document.getElementById("foo").innerHTML + "";

Thanks!

2
  • 5
    You can't do that (unless you're in the global scope and want to iterate through the properties on window). You might want to consider using an Object instead; i.e. var o = {foo: ["cool", "cool"]}; Now say you have var x = o.foo; you can iterate over o to find key using o[key] === x Commented Feb 12, 2014 at 1:20
  • 1
    Can you elaborate on the code you want to write? It's not clear how the above code fragment is called or what you expect to happen. If we understand what you are trying to do, maybe we can come up with a solution that doesn't involve knowing the variable name. For example, why not just pass the string "foo" to the function? The value of foo is never used. Commented Feb 12, 2014 at 1:28

2 Answers 2

1

You're looking at this the wrong way round - to answer this question directly

given foo, how do I get "foo"?

Well, the answer is... type "foo" in your code.

You know you want the string representation of the foo variable name when you write your code, so there's no scenario where the string value you want would be anything other than "foo", right?

It's true that you can reference a property foo, for example of the window object, using window["foo"] but that's the other way round too - you have to know it's foo you want, and deliberately use "foo" to get at it. So there's an example - you know what string to use, "foo", at compile time - it couldn't possibly be anything else.

Sign up to request clarification or add additional context in comments.

Comments

1

If it's a global variable, you get it as global object property: window in browsers and global in NodeJS. Otherwise, you don't.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.