September 29, 2013

How to turn variable name into string in JS?

Jehan’s Question:

I am trying to write a convenience wrapper for console.log, and I would like to print any variables passed in along with their contents.

Can I turn a variable name into a string in js?

There is a possibility. And here is how

var passed_variable = '65'; // The actual variable
var varname = 'passed_variable'; // The name of the variable in another variable

Now, pass the varname around but not the actual variable. When you need to the value of the variable you can simply do :

console.log(varname, ' : ', window[varname]); // Outputs, passed_variable : 65

I hope you find a way not to use this. 🙂

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!