JavaScript variable and assignment exercise

Download this page and open with Dreamweaver. Or right click and select "View Source", then cut and paste the code to Dreamweaver.

Task 1

Add <script> tags somewhere in the source code for this page and inside them:

  1. Create a new variable called myname and assign it a string containing your name
  2. Create a new variable called myage and assign it your age as a decimal number
  3. Create a new variable called amwelsh and assign it a boolean value of "true" or "false" depending on whether you agree with the statement "I am Welsh"

Task 2

Paste the following code into the page at the point indicated below:

<script type="text/javascript">
// This code is used to write lines of text into the page
	document.write("My name is " + myname + "<br/>");  
	document.write("My age is " + myage + "<br/>");                                    
	if (amwelsh) {
 		document.write("I am Welsh");
	}
	else {
 		document.write("I am not Welsh");		
	}
</script>

Task 3

Make sure you have saved this page. Then save again with a different filename so you do not overwrite the exercise.

Try changing the values in the variables you have set, see how those changes are reflected in the page that results.

Extension

Create a new pair of <script> tags with the correct attributes.

Into this block add the following JavaScript:

Prompt

Create a prompt() method to spawn a text entry box which will ask the user for their name. Create a new variable and assign the response of the prompt() to it. The code should look something like this:

// the text [text or variable] is a note and should be removed.
var variableName = prompt([text or variable]);

Confirm

Similar to prompt(), confirm() spawns a window which can display text and which asks the user for feedback. In this case the only feedback which can be provided is by pressing buttons labeled either "Okay" or "Cancel". The confirm() box returns a boolean value back to the script rather than the user supplied text. Use confirm() like this:

// the text [text or variable] is a note and should be removed.
var variableName = confirm([text or variable]);

Add in a line asking the user to confirm if they are over the age of 18. Collect their response in another new variable.

Alert

The alert() method spawns a box displaying whatever text is passed to it. The user only has the option of clicking an "okay" button to remove this window so it does not provide any feedback to the rest of the script.

Create a new variable which uses concatentation to join the string with the user's name and the boolean which holds the result of the age check.

Add an alert() method to display the result contained in the final variable. Use it like this:

// the text [text or variable] is a note and should be removed.
alert([text or variable]);