Javascript: Reference a variable name from the variable itself
While I'm not aware of such a possibility, I'd wanted to share a small idea:
Object.prototype.log = function(with_message) {
console.log(with_message + ":" + this);
}
var x = "string";
x.log("x");
Like I said, a small idea.
Solution - (for your actual use case) - console.log({foo})
In ES6 IdentifierReference
s are being accepted as PropertyDefinition
s on the ObjectLiteral
's PropertyDefinitionList
(see compatibility chart):
The variable name is being set to the Object
's Property
's key
and the variable value is being set to the Object
's Property
's value
.
As console.log
shows Object
s with their Propertiy
/ies' key
s and value
s you can use that to see both your variable's name and value by invoking console.log({foo})
.
Note that when you initialize a single anonymous
object
with several variables as I did in the secondconsole.log
while they appear in the same order as initialized here in the snippet's output they might get reordered (alphabetically) elsewhere.
var testint = 3
var teststring = "hi"
var testarr = ["one", 2, (function three(){})]
var testobj = {4:"four", 5:"five", nested:{6:"six",7:"seven"}}
console.log({testint})
console.log({testint, teststring, testarr, testobj})
Answer - (to the question title) - Object.keys({foo})[0]
You can also use this shorthand Object Initializer
together with Object.keys()
to straightly access the variable name:
var name = "value"
console.log(Object.keys({name})[0])
The reason it doesn't work is because the variable foo
is not accessable to the function varlog
! foo
is declared in someRandomFunction, and is never passed into varlog
, so varlog
has no idea what the variable foo is! You can solve this problem by passing the variable foo
into the function(or using some sort of closure to make foo
in the scope of varlog
) along with its string representation, but otherwise, I think you are out of luck.
Hope this helps.