var abc = '123'
var def = '456'
need to write somefuntion()
which convert variable name into string
like
alert ("value of" +somefuntion(abc) +"is"+ abc +"and value of" +somefuntion(def)+" is"+def );
should be like this
alert ("value of abc is 123 and value of def is 456")
i have searched and tried few solution and idk how this link can help cuz i know you will say its duplicate but i tried it and it didnt work
How to turn variable name into string in JS?
In Javascript, you can't actually have 2 variables made with different goals and have the same name in the same scope . Basically, there're 2 types of scope: global and local . Global scope is what you're facing making 2 variables with the same name in different files.
When you copy an object b = a both variables will point to the same address. This behavior is called copy by reference value. Strictly speaking in Ruby and JavaScript everything is copied by value. When it comes to objects though, the values happen to be the memory addresses of those objects.
Variable names are pretty flexible as long as you follow a few rules: Start them with a letter, underscore _, or dollar sign $. After the first letter, you can use numbers, as well as letters, underscores, or dollar signs. Don't use any of JavaScript's reserved keywords.
Use the code below.
const abc = '123';
const def = '456';
const varToString = varObj => Object.keys(varObj)[0]
alert ("value of " +varToString({def}) +" is "+ def +" and value of " +varToString({abc})+" is "+abc );
What this basicly does is, you pass the variable to varToString
as an object using {variable}
. varToString
then returns an array
with the passed variable as value.
[
"abc"
]
We grab this value using the [0]
selector (Object.keys(varObj)[0]). Now it returns
abc
Yes, you can do it:
function getVariableName(v) {
for (var key in window) {
if (window[key] === v)
return key;
}
}
var abc = '123';
var def = '456'
alert ("value of " + getVariableName(abc) +" is "+ abc +" and value of " + getVariableName(def) + " is " + def);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With