Print / display a JavaScript variable's name instead of it's value - javascript

Is it possible to print / display a JavaScript variable's name? For example:
var foo=5;
var bar=6;
var foobar=foo+bar;
document.write(foo+ "<br>");
document.write(bar+ "<br>");
document.write(foobar + "<br>");
How would we print the variable's names so the output would be:
foo
bar
foobar
Rather than:
5
6
11

You can put the variables in an object then easily print them this way: http://jsfiddle.net/5MVde/7/
See fiddle for everything, this is the JavaScript...
var x = {
foo: 5,
bar: 6,
foobar: function (){
var that=this;
return that.foo+that.bar
}
};
var myDiv = document.getElementById("results");
myDiv.innerHTML='Variable Names...';
for(var variable in x)
{
//alert(variable);
myDiv.innerHTML+='<br>'+variable;
}
myDiv.innerHTML+='<br><br>And their values...';
myDiv.innerHTML+='<br>'+x.foo+'<br>'+x.bar+'<br>'+x.foobar();
The JavaScript for...in statement loops through the properties of an object.
Another variation (thanks #elclanrs) if you don't want foobar to be a function: http://jsfiddle.net/fQ5hE/2/

Utils = {
eventRegister_globalVariable : function(variableName,handlers){
eventRegister_JsonVariable(this,variableName,handlers);
},
eventRegister_jsonVariable : function(jsonObj,variableName,handlers){
if(jsonObj.eventRegisteredVariable === undefined) {
jsonObj.eventRegisteredVariable={};//this Object is used for trigger event in javascript variable value changes ku
}
Object.defineProperty(jsonObj, variableName , {
get: function() {
return jsonObj.eventRegisteredVariable[variableName] },
set: function(value) {
jsonObj.eventRegisteredVariable[variableName] = value; handlers(jsonObj.eventRegisteredVariable[variableName]);}
});
}

Another possible solution can be "Object.keys(this)".... This will give you all the variable names in an array.

Related

Is it possible to get the object name passed into a function as a variable from within the function [duplicate]

Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)
I would like to do like this:
var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
UPDATE
I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:
FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
From another program:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
In PHP:
How to get a variable name as a string in PHP?
Like Seth's answer, but uses Object.keys() instead:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
In ES6, you could write something like:
let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
for(let varName in nameObject) {
return varName;
}
}
let varName = getVarNameFromObject(nameObject);
console.log(varName);
Not really the best looking thing, but it gets the job done.
This leverages ES6's object destructuring.
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
Get a string from any valid Javascript (variable, class):
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,'');
Examples:
nameOf(() => myVariable) // myVariable
nameOf(() => myVariable.name) // myVariable.name
nameOf(() => myVariable.name.length) // myVariable.name.length
nameOf(() => myVariable.name[10]) // myVariable.name[10]
nameOf(() => MySuperClass) // MySuperClass
Probably pop would be better than indexing with [0], for safety (variable might be null).
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${myFirstName}'`);
// returns "Variable myFirstName with value 'John'"
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
This works for basic expressions
const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
Example
nameof(() => options.displaySize);
Snippet:
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);
var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];
This isn't able to be made into a function as it returns the name of the function's variable.
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
Edit: Thanks to #Madeo for pointing out how to make this into a function.
function debugVar(varObj) {
var varName = Object.keys(varObj)[0];
console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}
You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.
Shortest way I have found so far to get the variables name as a string:
const name = obj => Object.keys(obj)[0];
const whatsMyName = "Snoop Doggy Dogg";
console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
// Get John’s properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John’s properties
var message = 'John’s properties are: ' + properties.join(', ');
document.write(message);
best way using Object.keys();
example : for getting multi variables names in global scope
// multi variables for testing
var x = 5 , b = true , m = 6 , v = "str";
// pass all variables you want in object
function getVarsNames(v = {}){
// getting keys or names !
let names = Object.keys(v);
// return array contain all names of variables
return names;
}
// testing if that work or not
let VarsNames = getVarsNames({x , b , m , v});
console.log(VarsNames); // output is array [x , b , m , v]
This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:
var myFirstName = "Danilo";
var varName = Object.keys({myFirstName:0})[0];
console.log(varName);
Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
For those who would like to print variableName and variableValue for debugging purposes, here is a function:
const printNameValue = (v)=> {
var varName = (v).toString().replace(/[ |\(\)=>]/g, '')
var varValue = (v)()
// neat : console.log(varName,varValue);
// with some coloring :
console.log("\033[1;96m[\033[1;33m " + varName + " :\033[0;0m " + varValue+"\033[1;96m ]\033[0;0m");
}
Example:
const myNiceVariable = 1234
call:
printNameValue(()=> myNiceVariable )
result:
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
var height = 120;
testAlert(height);
This should display:
height: 120
This can be done like this:
function testAlert(ta)
{
a = window[ta];
alert(ta + ': ' + a);
}
var height = 120;
testAlert("height");
// displays: height: 120
So I use the string "height" and turn that into a variable height using the window[] command.
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
var jack = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(jack));
Will write to the window 'jack'.
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){
let strX = "";
function replacer(key, value){
if (value === undefined){return "undef"}
return value
}
for (let arg of arguments){
let lastChar;
if (typeof arg!== "string"){
let _arg = JSON.stringify(arg, replacer);
_arg = _arg.replace('{',"");
_arg = _arg.replace('}',"");
_arg = _arg.replace(/:/g,"=");
_arg = _arg.replace(/"/g,"");
strX+=_arg;
}else{
strX+=arg;
lastChar = arg[arg.length-1];
}
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
}
console.log(strX)
}
let a = 42, b = 3, c;
debugVar("Begin:",{a,b,c},"end")
If you're looking for something quick and dirty, this might work:
var zox = 150;
cl("zox");
function cl(c) {
console.log(c + ': ' + this[c]); // zox: 150
}
No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

Trying to display js variables in html body [duplicate]

In PHP you can do amazing/horrendous things like this:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
Is there any way of doing something like this with Javascript?
E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?
Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).
So if you create variables like this:
var a = 1,
b = 2,
c = 3;
In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).
Those can get accessed by using the "dot" or "bracket" notation:
var name = window.a;
or
var name = window['a'];
This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:
function foobar() {
this.a = 1;
this.b = 2;
var name = window['a']; // === undefined
console.log(name);
name = this['a']; // === 1
console.log(name);
}
new foobar();
new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:
var a = 1,
b = 2;
Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).
eval is one option.
var a = 1;
var name = 'a';
document.write(eval(name)); // 1
Warning: Note that using the eval() function is not recommended if you don't know what you are doing, since it brings multiple security issues. Use something else unless absolutely necessary. See the MDN page for eval for more info.
You can use the window object to get at it .
window['myVar']
window has a reference to all global variables and global functions you are using.
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
This is an example :
for(var i=0; i<=3; i++) {
window['p'+i] = "hello " + i;
}
alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3
Another example :
var myVariable = 'coco';
window[myVariable] = 'riko';
alert(coco); // display : riko
So, the value "coco" of myVariable becomes a variable coco.
Because all the variables in the global scope are properties of the Window object.
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.
Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.
var id = "abc";
var mine = {};
mine[id] = 123;
console.log(mine.abc);
gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.
var mine = {};
mine.abc = 123;
console.log(mine["a"+"bc"]);
If you don't want to use a global object like window or global (node), you can try something like this:
var obj = {};
obj['whatever'] = 'There\'s no need to store even more stuff in a global object.';
console.log(obj['whatever']);
2019
TL;DR
eval operator can run string expression in the context it called and return variables from that context;
literal object theoretically can do that by write:{[varName]}, but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. but #Axel Heider has a good approaching.
The solution is eval.
almost most forgotten operator. ( think most one is with() )
eval operator can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamically return a variable's value in function's context.
example:
function exmaple1(){
var a = 1, b = 2, default = 3;
var name = 'a';
return eval(name)
}
example1() // return 1
function example2(option){
var a = 1, b = 2, defaultValue = 3;
switch(option){
case 'a': name = 'a'; break;
case 'b': name = 'b'; break;
default: name = 'defaultValue';
}
return eval (name);
}
example2('a') // return 1
example2('b') // return 2
example2() // return 3
Note that I always write explicitly the expression eval will run.
To avoid unnecessary surprises in the code. eval is very strong
But I'm sure you know that already
BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid
functopn example( varName ){
var var1 = 'foo', var2 ='bar'
var capture = {[varName]}
}
example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`
I needed to draw multiple FormData on the fly and object way worked well
var forms = {}
Then in my loops whereever i needed to create a form data i used
forms["formdata"+counter]=new FormData();
forms["formdata"+counter].append(var_name, var_value);
This is an alternative for those who need to export a dynamically named variable
export {
[someVariable]: 'some value',
[anotherVariable]: 'another value',
}
// then.... import from another file like this:
import * as vars from './some-file'
Another alternative is to simply create an object whose keys are named dynamically
const vars = { [someVariable]: 1, [otherVariable]: 2 };
// consume it like this
vars[someVariable];
use Object is great too.
var a=123
var b=234
var temp = {"a":a,"b":b}
console.log(temp["a"],temp["b"]);
Although this have an accepted answer I would like to add an observation:
In ES6 using let doesn't work:
/*this is NOT working*/
let t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);
However using var works
/*this IS working*/
var t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);
I hope this may be useful to some.
This will do exactly what you done in php:
var a = 1;
var b = 2;
var ccc = 3;
var name = 'a';
console.log( window[name] ); // 1
Simplest solution : Create an array of objects that every object has two field (variableName,variableValue)
let allVariables = [];
for (let i = 0; i < 5; i++)
allVariables.push({ variableName: 'variable' + i, variableValue: i * 10 });
for (let i = 0; i < allVariables.length; i++)
console.log(allVariables[i].variableName + ' is ' + allVariables[i].variableValue);
OutPut :
variable0 is 0
variable1 is 10
variable2 is 20
variable3 is 30
variable4 is 40
console.log(allVariables) json :
[
{
"variableName": "variable0",
"variableValue": 0
},
{
"variableName": "variable1",
"variableValue": 10
},
{
"variableName": "variable2",
"variableValue": 20
},
{
"variableName": "variable3",
"variableValue": 30
},
{
"variableName": "variable4",
"variableValue": 40
}
]
what they mean is no, you can't.
there is no way to get it done.
so it was possible you could do something like this
function create(obj, const){
// where obj is an object and const is a variable name
function const () {}
const.prototype.myProperty = property_value;
// .. more prototype
return new const();
}
having a create function just like the one implemented in ECMAScript 5.
eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:
function createVariable(varName,varContent)
{
var scriptStr = "var "+varName+"= \""+varContent+"\""
var node_scriptCode = document.createTextNode( scriptStr )
var node_script = document.createElement("script");
node_script.type = "text/javascript"
node_script.appendChild(node_scriptCode);
var node_head = document.getElementsByTagName("head")[0]
node_head.appendChild(node_script);
}
createVariable("dynamicVar", "some content")
console.log(dynamicVar)
Here's pure javascript solution which is not dependant on the global this of the runtime environment. Simple to achieve using object destructuring.
const dynamicVar = (nameValue, value) => {
const dynamicVarObj = {
[nameValue]: value
}
return dynamicVarObj;
}
const nameToUse = "myVar";
const value = 55;
const { myVar } = dynamicVar(nameToUse, value);
console.log(myVar); // prints 55
It is always better to use create a namespace and declare a variable in it instead of adding it to the global object. We can also create a function to get and set the value
See the below code snippet:
//creating a namespace in which all the variables will be defined.
var myObjects={};
//function that will set the name property in the myObjects namespace
function setName(val){
myObjects.Name=val;
}
//function that will return the name property in the myObjects namespace
function getName(){
return myObjects.Name;
}
//now we can use it like:
setName("kevin");
var x = getName();
var y = x;
console.log(y) //"kevin"
var z = "y";
console.log(z); //"y"
console.log(eval(z)); //"kevin"
In this similar way, we can declare and use multiple variables. Although this will increase the line of code but the code will be more robust and less error-prone.

How to print the variable name it self in javascript console [duplicate]

Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)
I would like to do like this:
var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
UPDATE
I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:
FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
From another program:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
In PHP:
How to get a variable name as a string in PHP?
Like Seth's answer, but uses Object.keys() instead:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
In ES6, you could write something like:
let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
for(let varName in nameObject) {
return varName;
}
}
let varName = getVarNameFromObject(nameObject);
console.log(varName);
Not really the best looking thing, but it gets the job done.
This leverages ES6's object destructuring.
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
Get a string from any valid Javascript (variable, class):
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,'');
Examples:
nameOf(() => myVariable) // myVariable
nameOf(() => myVariable.name) // myVariable.name
nameOf(() => myVariable.name.length) // myVariable.name.length
nameOf(() => myVariable.name[10]) // myVariable.name[10]
nameOf(() => MySuperClass) // MySuperClass
Probably pop would be better than indexing with [0], for safety (variable might be null).
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${myFirstName}'`);
// returns "Variable myFirstName with value 'John'"
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
This works for basic expressions
const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
Example
nameof(() => options.displaySize);
Snippet:
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);
var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];
This isn't able to be made into a function as it returns the name of the function's variable.
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
Edit: Thanks to #Madeo for pointing out how to make this into a function.
function debugVar(varObj) {
var varName = Object.keys(varObj)[0];
console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}
You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.
Shortest way I have found so far to get the variables name as a string:
const name = obj => Object.keys(obj)[0];
const whatsMyName = "Snoop Doggy Dogg";
console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
// Get John’s properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John’s properties
var message = 'John’s properties are: ' + properties.join(', ');
document.write(message);
best way using Object.keys();
example : for getting multi variables names in global scope
// multi variables for testing
var x = 5 , b = true , m = 6 , v = "str";
// pass all variables you want in object
function getVarsNames(v = {}){
// getting keys or names !
let names = Object.keys(v);
// return array contain all names of variables
return names;
}
// testing if that work or not
let VarsNames = getVarsNames({x , b , m , v});
console.log(VarsNames); // output is array [x , b , m , v]
This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:
var myFirstName = "Danilo";
var varName = Object.keys({myFirstName:0})[0];
console.log(varName);
Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
For those who would like to print variableName and variableValue for debugging purposes, here is a function:
const printNameValue = (v)=> {
var varName = (v).toString().replace(/[ |\(\)=>]/g, '')
var varValue = (v)()
// neat : console.log(varName,varValue);
// with some coloring :
console.log("\033[1;96m[\033[1;33m " + varName + " :\033[0;0m " + varValue+"\033[1;96m ]\033[0;0m");
}
Example:
const myNiceVariable = 1234
call:
printNameValue(()=> myNiceVariable )
result:
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
var height = 120;
testAlert(height);
This should display:
height: 120
This can be done like this:
function testAlert(ta)
{
a = window[ta];
alert(ta + ': ' + a);
}
var height = 120;
testAlert("height");
// displays: height: 120
So I use the string "height" and turn that into a variable height using the window[] command.
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
var jack = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(jack));
Will write to the window 'jack'.
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){
let strX = "";
function replacer(key, value){
if (value === undefined){return "undef"}
return value
}
for (let arg of arguments){
let lastChar;
if (typeof arg!== "string"){
let _arg = JSON.stringify(arg, replacer);
_arg = _arg.replace('{',"");
_arg = _arg.replace('}',"");
_arg = _arg.replace(/:/g,"=");
_arg = _arg.replace(/"/g,"");
strX+=_arg;
}else{
strX+=arg;
lastChar = arg[arg.length-1];
}
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
}
console.log(strX)
}
let a = 42, b = 3, c;
debugVar("Begin:",{a,b,c},"end")
If you're looking for something quick and dirty, this might work:
var zox = 150;
cl("zox");
function cl(c) {
console.log(c + ': ' + this[c]); // zox: 150
}
No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

Get name of object In String Javascript [duplicate]

Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)
I would like to do like this:
var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
UPDATE
I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:
FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
From another program:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
In PHP:
How to get a variable name as a string in PHP?
Like Seth's answer, but uses Object.keys() instead:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
In ES6, you could write something like:
let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
for(let varName in nameObject) {
return varName;
}
}
let varName = getVarNameFromObject(nameObject);
console.log(varName);
Not really the best looking thing, but it gets the job done.
This leverages ES6's object destructuring.
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
Get a string from any valid Javascript (variable, class):
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,'');
Examples:
nameOf(() => myVariable) // myVariable
nameOf(() => myVariable.name) // myVariable.name
nameOf(() => myVariable.name.length) // myVariable.name.length
nameOf(() => myVariable.name[10]) // myVariable.name[10]
nameOf(() => MySuperClass) // MySuperClass
Probably pop would be better than indexing with [0], for safety (variable might be null).
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${myFirstName}'`);
// returns "Variable myFirstName with value 'John'"
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
This works for basic expressions
const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
Example
nameof(() => options.displaySize);
Snippet:
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);
var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];
This isn't able to be made into a function as it returns the name of the function's variable.
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
Edit: Thanks to #Madeo for pointing out how to make this into a function.
function debugVar(varObj) {
var varName = Object.keys(varObj)[0];
console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}
You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.
Shortest way I have found so far to get the variables name as a string:
const name = obj => Object.keys(obj)[0];
const whatsMyName = "Snoop Doggy Dogg";
console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
// Get John’s properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John’s properties
var message = 'John’s properties are: ' + properties.join(', ');
document.write(message);
best way using Object.keys();
example : for getting multi variables names in global scope
// multi variables for testing
var x = 5 , b = true , m = 6 , v = "str";
// pass all variables you want in object
function getVarsNames(v = {}){
// getting keys or names !
let names = Object.keys(v);
// return array contain all names of variables
return names;
}
// testing if that work or not
let VarsNames = getVarsNames({x , b , m , v});
console.log(VarsNames); // output is array [x , b , m , v]
This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:
var myFirstName = "Danilo";
var varName = Object.keys({myFirstName:0})[0];
console.log(varName);
Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
For those who would like to print variableName and variableValue for debugging purposes, here is a function:
const printNameValue = (v)=> {
var varName = (v).toString().replace(/[ |\(\)=>]/g, '')
var varValue = (v)()
// neat : console.log(varName,varValue);
// with some coloring :
console.log("\033[1;96m[\033[1;33m " + varName + " :\033[0;0m " + varValue+"\033[1;96m ]\033[0;0m");
}
Example:
const myNiceVariable = 1234
call:
printNameValue(()=> myNiceVariable )
result:
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
var height = 120;
testAlert(height);
This should display:
height: 120
This can be done like this:
function testAlert(ta)
{
a = window[ta];
alert(ta + ': ' + a);
}
var height = 120;
testAlert("height");
// displays: height: 120
So I use the string "height" and turn that into a variable height using the window[] command.
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
var jack = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(jack));
Will write to the window 'jack'.
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){
let strX = "";
function replacer(key, value){
if (value === undefined){return "undef"}
return value
}
for (let arg of arguments){
let lastChar;
if (typeof arg!== "string"){
let _arg = JSON.stringify(arg, replacer);
_arg = _arg.replace('{',"");
_arg = _arg.replace('}',"");
_arg = _arg.replace(/:/g,"=");
_arg = _arg.replace(/"/g,"");
strX+=_arg;
}else{
strX+=arg;
lastChar = arg[arg.length-1];
}
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
}
console.log(strX)
}
let a = 42, b = 3, c;
debugVar("Begin:",{a,b,c},"end")
If you're looking for something quick and dirty, this might work:
var zox = 150;
cl("zox");
function cl(c) {
console.log(c + ': ' + this[c]); // zox: 150
}
No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

Javascript shows variable string instead of calling variable [duplicate]

In PHP you can do amazing/horrendous things like this:
$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1
Is there any way of doing something like this with Javascript?
E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?
Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).
So if you create variables like this:
var a = 1,
b = 2,
c = 3;
In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).
Those can get accessed by using the "dot" or "bracket" notation:
var name = window.a;
or
var name = window['a'];
This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:
function foobar() {
this.a = 1;
this.b = 2;
var name = window['a']; // === undefined
console.log(name);
name = this['a']; // === 1
console.log(name);
}
new foobar();
new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:
var a = 1,
b = 2;
Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).
eval is one option.
var a = 1;
var name = 'a';
document.write(eval(name)); // 1
Warning: Note that using the eval() function is not recommended if you don't know what you are doing, since it brings multiple security issues. Use something else unless absolutely necessary. See the MDN page for eval for more info.
You can use the window object to get at it .
window['myVar']
window has a reference to all global variables and global functions you are using.
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
This is an example :
for(var i=0; i<=3; i++) {
window['p'+i] = "hello " + i;
}
alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3
Another example :
var myVariable = 'coco';
window[myVariable] = 'riko';
alert(coco); // display : riko
So, the value "coco" of myVariable becomes a variable coco.
Because all the variables in the global scope are properties of the Window object.
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.
Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var notation but Javascript doesn't need to because property keys are interchangeable with array keys.
var id = "abc";
var mine = {};
mine[id] = 123;
console.log(mine.abc);
gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.
var mine = {};
mine.abc = 123;
console.log(mine["a"+"bc"]);
If you don't want to use a global object like window or global (node), you can try something like this:
var obj = {};
obj['whatever'] = 'There\'s no need to store even more stuff in a global object.';
console.log(obj['whatever']);
2019
TL;DR
eval operator can run string expression in the context it called and return variables from that context;
literal object theoretically can do that by write:{[varName]}, but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. but #Axel Heider has a good approaching.
The solution is eval.
almost most forgotten operator. ( think most one is with() )
eval operator can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamically return a variable's value in function's context.
example:
function exmaple1(){
var a = 1, b = 2, default = 3;
var name = 'a';
return eval(name)
}
example1() // return 1
function example2(option){
var a = 1, b = 2, defaultValue = 3;
switch(option){
case 'a': name = 'a'; break;
case 'b': name = 'b'; break;
default: name = 'defaultValue';
}
return eval (name);
}
example2('a') // return 1
example2('b') // return 2
example2() // return 3
Note that I always write explicitly the expression eval will run.
To avoid unnecessary surprises in the code. eval is very strong
But I'm sure you know that already
BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid
functopn example( varName ){
var var1 = 'foo', var2 ='bar'
var capture = {[varName]}
}
example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`
I needed to draw multiple FormData on the fly and object way worked well
var forms = {}
Then in my loops whereever i needed to create a form data i used
forms["formdata"+counter]=new FormData();
forms["formdata"+counter].append(var_name, var_value);
This is an alternative for those who need to export a dynamically named variable
export {
[someVariable]: 'some value',
[anotherVariable]: 'another value',
}
// then.... import from another file like this:
import * as vars from './some-file'
Another alternative is to simply create an object whose keys are named dynamically
const vars = { [someVariable]: 1, [otherVariable]: 2 };
// consume it like this
vars[someVariable];
use Object is great too.
var a=123
var b=234
var temp = {"a":a,"b":b}
console.log(temp["a"],temp["b"]);
Although this have an accepted answer I would like to add an observation:
In ES6 using let doesn't work:
/*this is NOT working*/
let t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);
However using var works
/*this IS working*/
var t = "skyBlue",
m = "gold",
b = "tomato";
let color = window["b"];
console.log(color);
I hope this may be useful to some.
This will do exactly what you done in php:
var a = 1;
var b = 2;
var ccc = 3;
var name = 'a';
console.log( window[name] ); // 1
Simplest solution : Create an array of objects that every object has two field (variableName,variableValue)
let allVariables = [];
for (let i = 0; i < 5; i++)
allVariables.push({ variableName: 'variable' + i, variableValue: i * 10 });
for (let i = 0; i < allVariables.length; i++)
console.log(allVariables[i].variableName + ' is ' + allVariables[i].variableValue);
OutPut :
variable0 is 0
variable1 is 10
variable2 is 20
variable3 is 30
variable4 is 40
console.log(allVariables) json :
[
{
"variableName": "variable0",
"variableValue": 0
},
{
"variableName": "variable1",
"variableValue": 10
},
{
"variableName": "variable2",
"variableValue": 20
},
{
"variableName": "variable3",
"variableValue": 30
},
{
"variableName": "variable4",
"variableValue": 40
}
]
what they mean is no, you can't.
there is no way to get it done.
so it was possible you could do something like this
function create(obj, const){
// where obj is an object and const is a variable name
function const () {}
const.prototype.myProperty = property_value;
// .. more prototype
return new const();
}
having a create function just like the one implemented in ECMAScript 5.
eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:
function createVariable(varName,varContent)
{
var scriptStr = "var "+varName+"= \""+varContent+"\""
var node_scriptCode = document.createTextNode( scriptStr )
var node_script = document.createElement("script");
node_script.type = "text/javascript"
node_script.appendChild(node_scriptCode);
var node_head = document.getElementsByTagName("head")[0]
node_head.appendChild(node_script);
}
createVariable("dynamicVar", "some content")
console.log(dynamicVar)
Here's pure javascript solution which is not dependant on the global this of the runtime environment. Simple to achieve using object destructuring.
const dynamicVar = (nameValue, value) => {
const dynamicVarObj = {
[nameValue]: value
}
return dynamicVarObj;
}
const nameToUse = "myVar";
const value = 55;
const { myVar } = dynamicVar(nameToUse, value);
console.log(myVar); // prints 55
It is always better to use create a namespace and declare a variable in it instead of adding it to the global object. We can also create a function to get and set the value
See the below code snippet:
//creating a namespace in which all the variables will be defined.
var myObjects={};
//function that will set the name property in the myObjects namespace
function setName(val){
myObjects.Name=val;
}
//function that will return the name property in the myObjects namespace
function getName(){
return myObjects.Name;
}
//now we can use it like:
setName("kevin");
var x = getName();
var y = x;
console.log(y) //"kevin"
var z = "y";
console.log(z); //"y"
console.log(eval(z)); //"kevin"
In this similar way, we can declare and use multiple variables. Although this will increase the line of code but the code will be more robust and less error-prone.

Categories

Resources