Javascript Tutorial - Lesson 1 High-Low

Javascript is a programming language consisting of executable statements or instructions that are generally executed sequentially. Statements are terminated by a semicolon. Each statement performs a specific task such as define variables, operate on variables and constants, set the value of a variable, test a conditon to determine what to do, define a function or call a function to execute.

A function is a sequence of instructions that are executed when the function is called. It is defined as follows:
function name(){
any number of statements;
}
Name is chosen for the function to use to call the function for execution. Inside of () after the name can be any number of variables (arguments) to be used by the function. The braces { and } delimit the statements comprising the function.

Following is an example program along with HTML Form elements to illustrate Javascript programming:

Think of a number from one to one hundred and I will guess it.

Javascript statements Comments

<script language="javascript">
var g,minimum,maximum;

function start(){
minimum=1;
maximum=100;
g=minimum-1;
too_low();}

function too_low(){
minimum=g+1;
g=Math.floor((minimum+maximum)/2);
document.formg.guess.value=g;}

function too_high(){
maximum=g-1;
g=Math.floor((maximum+minimum)/2);
document.formg.guess.value=g;}

function correct(){
document.formg.guess.value=g+" is correct";}
</script>

Introduces a section of Javascript
declare labels for variables

declares a function called start()
sets the variable minimum to 1
sets the variable maximoum to 100
sets initial value for g to minimum -1
call the function too-low()

declares a function called too_low()
sets the minimum to the last guess (g) + 1
computes a new guess halfway between minimum & maximum
outputs it to the guess textbox

declares a function called too_high()
sets the new maximum to the last guess (g) - 1
computes a new guess halfway between minimum & maximum
outputs it to the guess textbox

declares a javascript function called correct()
outputs the message that g is the correct guess
terminates Javascript section
HTML Comments

<form name="formg">
<input type=text name=guess size=24 value=""><br>
<input type=button value="Start" onClick="start();">
<input type=button value="Too low" onClick="too_low();">
<input type=button value="Too high" onClick="too_high();">
<input type=button value="Match" onClick="correct();">
</form>

declares a form called formg
defines a textbox called guess
defines a button that calls start()
defines a button that calls too_low()
defines a button that calls too_high()
defines a button that calls correct()
defines the end of formg

Homework Assignment

Rewrite the high-low program to guess a number from 1 to 2000. Place it into an html document with the Javascript in the head and the form in the body. Add a picture or two to illustrate the operation of the program.