Is there a way to get name of a variable declared by var, let, const? Or is it only possible for class and function variables?
Asked
Active
Viewed 81 times
1
-
2No, it's not possible. Variable are only labels for values - once you're looking at a value, there is no way to know which binding it came from. – VLAZ Jan 17 '20 at 13:20
-
1Does this answer your question? [get variable name into string in javascript](https://stackoverflow.com/questions/47468361/get-variable-name-into-string-in-javascript) – Calvin Nunes Jan 17 '20 at 13:23
1 Answers
1
I think this would be the only way
let a = "A";
const b ="B";
var c = "C";
const scr = document.currentScript.innerText;
console.log(scr.match(/(var|let|const)\s+\w+/gm))

mplungjan
- 169,008
- 28
- 173
- 236
-
1This (parsing JS to find the what a value is associated with) is indeed the only way...but it doesn't work. Not generically. For example `let foo = "ba" + "r"` will not work. You can only use it if the values are hardcoded. And even then, there is a problem - `let x = 42; let y = 42; findBindingNameOf(x) //???` duplicated values cannot be looked up reliably - you can find that there are *some* variables that are set to `42` but not *which one* was passed in. – VLAZ Jan 17 '20 at 13:56
-
1I can find foo, x and y - that was all I tried with this code. Lack of usecase makes it hard to find what they want – mplungjan Jan 17 '20 at 14:02
-
Oh, I'm not blaming you or the code in any way. The question could definitely use more details. In fact, I suspect it is an XY problem. At any rate, I just wanted to mention the limitation. Although, now that I look at it - we both seem to have a different reading on the question. I thought OP wanted to do something like `findBindingNameOf(x)` and be able to get `"x"` out of it. But you did `findAllBindings()` (essentially) that returns all variable names. I can see how both are valid interpretations, so it just underlines how the question is unclear. – VLAZ Jan 17 '20 at 14:09
-
1Oh, in the case of "finding all variables", you need to split on comma, since a variable declaration can contain multiple ones `let a, b, c`. This makes the task both more complex to implement (e.g., what if it's `let a, b = 2, c` or they are even separated by newlines?) and even more like one should step back and figure out *why* this is needed before proceeding, as there is probably a better approach to solve whatever problem finding variables would solve. – VLAZ Jan 17 '20 at 14:12