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.
Asked
Active
Viewed 1,308 times
-1
-
1This is possible, yes. Can you add any attempts at solving the problem on your own? – Luca Kiebel Feb 12 '19 at 19:20
-
https://stackoverflow.com/questions/1441532/is-there-a-way-to-access-a-javascript-variable-using-a-string-that-contains-the-n – epascarello Feb 13 '19 at 04:14
2 Answers
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>

harshit pandey
- 126
- 6
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