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!

goelv
  • 2,774
  • 11
  • 32
  • 40
  • 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` – Paul S. Feb 12 '14 at 01: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. – Raymond Chen Feb 12 '14 at 01:28

2 Answers2

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.

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.

davnicwil
  • 28,487
  • 16
  • 107
  • 123