DEV Community 👩‍💻👨‍💻


Posted on

How to use integers/strings in arrays as variables?

As for now, I don't think you can make variables with js (theres no createVar function to my knowledge) so I thought that using arrays with strings could be a way to do it. I'm getting there, but there's a step im missing.

I've tried this:

var variableArray = [];
var variable=document.getElementById('numberValue').value;
var information=document.getElementById('textEditorValue');
function createVar(){

what I want it to output

["1:(information for the variable here)"]

and i want it to make it so when you do this:


I want it to output this:

(information for the first variable)

I'm trying a new method right now but i can't get it to work. Please help!

Top comments (4)

kallmanation profile image
Nathan Kallman

Why do you feel the need to "create" a variable?

It looks like you are trying to dynamically store user generated content... but for what purpose?

purplepotatobro profile image
PurplePotatoBro Author

Im making a notepad sort of html site.
There is a bar on the left where you have your text files which you can remove or add or open. You have a textfield where you type, but all if the things you've typed out need to be stored, so when you open another file, it can load the text of the other file, and not the one you just worked on. To have as many pages as you want, you need to have a lot of variables. Im definetely not going to type out a lot of variables when theres probably some easier way to have the code do it for you. So thats why i want to know how to make variables with code. Thank you if you share a way to do so

kallmanation profile image
Nathan Kallman

You're not too far off in concept. I think calling it "creating" or "assigning" variables will just confuse you though.

It's more adding/removing/modifying values in a data structure (in this case, just an array).

I made a simple example for you to hopefully answer some of the more specific details you may be struggling with.

I'll note that this is not production level code. A few things (of many) to improve:

  1. Avoid global variables
  2. Avoid functions doing both app logic and DOM effects

Thread Thread
purplepotatobro profile image
PurplePotatoBro Author

I finished my project a few hours ago, thanks!

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.