Back

Javascript

Variables

Example 1

Create a new document. Put the code below anywhere in your document. What does it do?

<script type="text/javascript>
prompt("What is your name?");
</script>

Example 2

We can use a variable to save information for later use. Try the code below anywhere in your document to see how it works.

<script type="text/javascript">
var name = prompt("What is your name?");
</script>

<script>
alert("Hello, " + name + "!");
</script>

Example 3

Here's another example of using variables. Start by including the following code in the body of your document. What does document.write do?

<script type="text/javascript">
document.write("<p>Hello, world!</p>");
</script>

Example 4

Now change the code to look like the example below. Save and preview. What do the variables do?

<script type="text/javascript">
var firstname = "Cookie";
var lastname = "Monster";
document.write("<p>Hello, " + firstname + "  " + lastname + "!</p>");
</script>

Example 5

How would you ask someone viewing your web page to enter his or her first name, and then write the first name into the document?

Example 6

Extra credit! How would you ask someone viewing your web page to select a color, and then change the color of the text to the color they chose?