Outputting a variable

So once you've declared (or created) a variable, you want to use it in your program. You could, for example, store strings, numbers, etc., in your variables. Then, you could manipulate the values of your variables. At some point, you have to show the values of those variables to the screen. Your variable, for instance, may hold the total amount the customer owes to your website for the items he or she is purchasing.

We won't create complex examples to show you how to output a value of a variable. To output a value of a variable, simply place the variable name as an argument inside the document.write method, as:

<script language="javascript">
var x
x = 50;
document.write (x); //prints the value of x
</script>

The above JavaScript code creates a variable called x (line 2) and sets it equal to 50 (line 2). On line 3, we use the document.write () method to print the value of the variable x to the screen. The following shows the output:

If your variable contains a string (a sequence of text containing letters, numbers and punctuation), printing that is the same as shown above. You just pass the variable name to the document.write () method to print a variable's value. The following shows an example of printing both a numerical and string values of variables.

<script language="javascript">
var x, message;
x = 50;
message = "x is equal to ";
document.write (message); // prints the value of the message variable
document.write (x); //prints the value of x
</script>

On line 4 (message = "x is equal to ";) above we assign a string value to our variable called message. Anytime you want to assign a string value to variable, simply use double or single quotation marks around it. Line 5, document.write (message);, we print the value of the variable message. Line 6 print the value of the variable x. Following shows the output of the above code: