get variable name into string in javascript

Ahtesham ul haq
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?

Red

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Get name of Variable a string in Javascript

Get global variable dynamically by name string in JavaScript

Get the name of a variable in a string

Variable name as a string in Javascript

Java get variable name as string

Get variable by name from a String

How to get the name of a variable as a string?

Convert string to variable name in JavaScript

JavaScript convert a string to a variable name?

Get the name of instance as string in Javascript

Javascript + build a dynamic variable name from a variable name and string

How to get a variable name as a string in PHP?

Get the string and append it before a variable name

Get a Swift Variable's Actual Name as String

How to get the name of a variable as a string in a loop?

How to get a button by variable name using a string?

Get query string variable name in Django

check if string variable name is a javascript fuction of an object

JavaScript object: access variable property by name as string

Javascript get short circuit variable name

Get the Variable name inside the function in javascript

How to get a variable value if variable name is stored as string?

Javascript - Get a function's name as a string

How to get call string variable to Javascript in laravel

Get variable contents from string using javascript

Get a string in a variable to create a dynamic link in Javascript

JavaScript get first name and last name from string as array

How to get value of variables in Scala, where name of variable is obtained as string

I have a string with a package name. Is it possible to get a package variable?