+ 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.
6 odpowiedzi
+ 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;
+ 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".
+ 2
Thank you very much for your help
+ 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.
+ 1
Hi Hasty Rei,
Can objects or arrays also be used as something similar?
Thank you
+ 1
you can use an array for that because js arrays are dynamic