How to Use Strings As Variables for JavaScript
- 1). Declare your variable with a tag. In JavaScript, that works with the tag "var."
- 2). Assign a name to your variable. For example, if you are creating a JavaScript code regarding a car, you can declare the name of the variable using the following code:
var carname;
In this example, the tag var notifies the server you are declaring a variable and naming it "carname." - 3). Assign your string. A string identifies what the name of the variable means. Using the example above, the car you are listing is a Volvo. You code would look like this:
var carname = "Volvo";
This tells the server you are declaring a variable named "carname" and the string assigned to it is "Volvo." - 4). Create the code to call your string. Writing this code will depend on what action in your JavaScript is using the variable. If you want the variable string to print out on the webpage you would use "document.write" to call the variable. For instances, to print the information contained in variable "carname" you would write:
document.write(carname);
The result would be "Volvo" printed on your page.