Functions


JavaScript allows you to define and call your own functions.

It is good programming practice to have the function appear before the code that calls it.

Functions do not have to return values, nor do you have to assign the value they return.

Variables that are define in the function are local to the function.

Try the following program out


// This is the function area

function largest(x,y)
  {var l = x;
   if (y>x) l= y;
   return l;}

// This is where the execution starts

var l = null;

while (true)
  {n = prompt("Enter A value, Cancel to end","###");
   if (n==null) break; // exit the loop

   // Convert the string to a number
   if (n.indexOf(".") != -1) // check to see if it is real or integer
    {n = parseFloat(n);}
   else
    {n = parseInt(n);}

   l = largest(l,n);}

document.write("Largest value was " + l);


Run the program

Back