Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Reference a variable name from the variable itself

Tags:

I want to create a quick function that will console.log a variable name and the value. I'd like the result of the function to show in the console: foo: bar.

My basic idea for the function looks like this:

function varlog(var_name) {     console.log(var_name + ": " + eval(var_name)); } 

And I'd call is thusly:

function someRandomFunction() {     var foo = "bar";     // ... some stuff happens     varlog("foo"); } 

This works if foo is global, but doesn't work in the example provided. Another option that also only works globally is using window[var_name] instead of the scary eval.

I don't think what I'm asking is possible, but I figured I'd throw it out there.

I'm spending a lot of time attempting to be lazy. My current method is just console.log('foo: ' + bar); which works just fine. But now I just want to know if this is possible.

Some other questions I referenced in searching for this / creating what I have now:

  • Variable name as a string in Javascript
  • How to convert variable name to string in JavaScript?
  • Javascript, refer to a variable using a string containing its name?
  • How to find JavaScript variable by its name

--

Edit: I'd love to just call varlog(foo), if the name "foo" can be derived from the variable.

like image 210
hookedonwinter Avatar asked Mar 22 '11 17:03

hookedonwinter


People also ask

How do you dynamically name a variable in JavaScript?

In JavaScript, dynamic variable names can be achieved by using 2 methods/ways given below. eval(): The eval() function evaluates JavaScript code represented as a string in the parameter. A string is passed as a parameter to eval(). If the string represents an expression, eval() evaluates the expression.

Can I use name as a variable in JavaScript?

Names are case sensitive (y and Y are different variables) Reserved words (like JavaScript keywords) cannot be used as names.

Can function name and variable name be same in JavaScript?

Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).


1 Answers

Solution - (for your actual use case) - console.log({foo})

In ES6 IdentifierReferences are being accepted as PropertyDefinitions 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 Objects with their Propertiy/ies' keys and values 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 second console.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])
like image 159
sqln00b Avatar answered Nov 07 '22 06:11

sqln00b