Working with Global Functions - Exercise

Contact Us or call 1-877-932-8228
Working with Global Functions - Exercise

Working with Global Functions

Duration: 10 to 15 minutes.

In this exercise, you will practice working with JavaScript's global functions.

  1. Open JavaScriptFunctions/Exercises/BuiltinFunctions.html for editing.
  2. Modify the file so that it outputs the sum of the two numbers entered by the user.

Code Sample:

JavaScriptFunctions/Exercises/BuiltinFunctions.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Built-in Functions</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	var userNum1, userNum2, numsAdded;
	userNum1 = window.prompt("Choose a number.", "");
	alert("You chose " + userNum1);
	userNum2 = window.prompt("Choose another number.", "");
	alert("You chose " + userNum2);
	numsAdded = userNum1 + userNum2;
</script>
</head>
<body>
<p>
	<script type="text/javascript">
		document.write(userNum1 + " + " + userNum2 + " = ");
		document.write(numsAdded + "<br/>");
	</script>
</p>
</body>
</html>

Challenge

Create a new HTML file that prompts the user for his name, the age at which he first worked on a computer, and his current age. After gathering this information, pop up an alert that tells the user how many years he's been working on a computer. The images below show the steps:

Notice that the program is able to deal with numbers followed by strings (e.g, "12 years old").

Solution:

JavaScriptFunctions/Solutions/BuiltinFunctions.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Built-in Functions</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	var userNum1, userNum1, numsAdded;
	userNum1 = window.prompt("Choose a number.", "");
	alert("You chose " + userNum1);
	userNum2 = window.prompt("Choose another number.", "");
	alert("You chose " + userNum2);
	numsAdded = Number(userNum1) + Number(userNum2);
</script>
</head>
<body>
<p>
	<script type="text/javascript">
		document.write(userNum1 + " + " + userNum2 + " = ");
		document.write(numsAdded + "<br/>");
	</script>
</p>
</body>
</html>

Challenge Solution:

JavaScriptFunctions/Solutions/BuiltInFunctions-challenge.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Built-in Functions</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	var userName = prompt("What's your name?", "");
	var age1 = prompt("How old were you when you first used a computer?", "");
	var age2 = prompt("How old are you now?", "");
	var diff = parseFloat(age2) - parseFloat(age1);
	alert(userName + ", you have used computers for " + diff + " years.");
</script>
</head>
<body>
	<p>Nothing to show here.</p>
</body>
</html>
Next