-1

How to create a variable using a user-defined name in JavaScript? I tried writing var a.value, where a is the id of the text field where the user will enter the variable name.

karel
  • 5,489
  • 46
  • 45
  • 50

2 Answers2

2

Yes, It is possible to create a variables using user-defined name. take this example.

var var_name = 'test_var';
const n = 120;
this[var_name] = n;
alert("printing using this[var_name]: "+this[var_name]);
alert("printing using test_var: "+test_var);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>

</head>
<body>

</body>
</html>
0

You can define an object with all your user-defined variables.

const VAR_NAME = 'myVar'
const VAR_VALUE = 'myValue'

var obj = {
  [VAR_NAME]: VAR_VALUE
}

console.log(obj)
console.log(obj[VAR_NAME])
vmf91
  • 1,897
  • 19
  • 27