Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get variable name into string in javascript [duplicate]

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?

like image 426
Ahtesham ul haq Avatar asked Nov 24 '17 07:11

Ahtesham ul haq


People also ask

Can you have two variables with the same name JavaScript?

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.

What is copy by value and copy by reference in JavaScript?

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.

How do you name a variable in JavaScript?

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.


2 Answers

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
like image 107
Red Avatar answered Oct 13 '22 02:10

Red


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);
like image 42
Gal Shaboodi Avatar answered Oct 13 '22 03:10

Gal Shaboodi