Practice Review: Using Functions with Conditionals

Try this exercise to see how well you understood working with functions and conditionals. Copy the code into your favorite editor and display an "interactive" web page that uses a function and a "while" statement to compute the current speed. This exercise does not count towards your grade. It is just for practice!

Functions represent metadata as they provide some abstracted behavior to be used by data from the web page, and so the function definitions are generally found in the head of a document. Calling functions is part of the information on the web page and occurs in the body of the document. The following is an example of a web page that prompts the user for values of distance and time and prints out the speed. The program exits when a value of "-1" is entered for the distance.


Sentinel Control loop program using a function to calculate speed
<html>
<head>
<title>Speed web page.</title>
<script>
function speed(distance, time) {
return distance / time;
}
</script>
</head>
<body>
<script>
let d = prompt("Enter the distance, -1 to end")
while (d != -1) {
  let t = prompt("Enter the time to travel the distance")
 alert(d / t);
 d = prompt("Enter the distance, or -1 to end")
}
</script>
</body>
</html>

Source: Charles W. Kann III, https://www.oercommons.org/courses/programming-for-the-web-from-soup-to-nuts-implementing-a-complete-gis-web-page-using-html5-css-javascript-node-js-mongodb-and-open-layers/view
This work is licensed under a Creative Commons Attribution 4.0 License.

Last modified: Tuesday, October 11, 2022, 5:10 PM