Can a JS script make its own variables without the developer making them at first? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can a JS script make its own variables without the developer making them at first?

I am very curious if a js script create variables by itself. For example if a user enters a character in prompt and that character becomes a variable to which stuff can be assigned. E.g. Function varcreate() { Var x = prompt(“Enter var name”) Var z = prompt(“Enter the string you want to add to ”+x) Var (x) = (“‘“z”’”) } If that is imposible to do in js, is any there any other way to do something similar to this? Thank you, beforehand.

17th Aug 2019, 1:13 PM
Kopamed [Active... ?]
Kopamed [Active... ?] - avatar
6 Answers
+ 6
Well, no. Users are not capable of altering the source code during runtime. As for something similar, it depends on what you are trying to achieve. You can use a map, wherein the key would be the "variable name" and the value would be whatever is stored. var myMap = {} var x = prompt("name") var y = prompt("value") myMap[x] = y;
17th Aug 2019, 1:26 PM
Hatsy Rei
Hatsy Rei - avatar
+ 7
JavaScript arrays are dynamic, so it is possible, but if you use an array, your user would only be able to specify the desired array slot (index) to store data, instead of being able to input a "variable name".
17th Aug 2019, 1:30 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Thank you very much for your help
17th Aug 2019, 1:31 PM
Kopamed [Active... ?]
Kopamed [Active... ?] - avatar
+ 2
Somehow yes, you need to create an object first. after that, you can create properties based on user input. https://code.sololearn.com/Wa5a5s5tGEZG/?ref=app and then you can access the value stored in the object by using the corresponding key.
17th Aug 2019, 4:45 PM
Gordon
Gordon - avatar
+ 1
Hi Hasty Rei, Can objects or arrays also be used as something similar? Thank you
17th Aug 2019, 1:28 PM
Kopamed [Active... ?]
Kopamed [Active... ?] - avatar
+ 1
you can use an array for that because js arrays are dynamic
18th Aug 2019, 7:33 AM
Raghed Kahil
Raghed Kahil - avatar