LESSON 05 – FUNCTIONS

 

WHAT ARE THEY?

 

To non-programmers, you have probably referred to a function as a command.  It’s simply a word that makes something happen.  In fact, it calls a series of code that does something.  Before jumping into this, let’s consider functions in Math.

 

Another word for function is method.

 

One of the most famous functions is the square root function.  Let’s consider a small math example.

 

Math Example

 

Solve for x.  Note that the sqrt(44) is read as The square root of 44.

 

x = 15 + sqrt(44)

 

x = 15 + 6.63

 

x = 21.63

 

 

In the real world, to calculate the square root of 44, one probably used a calculator.  The calculator has a built-in function that automatically calculates the square root of the number provided.

 

BUILT-IN MATH FUNCTIONS

 

Javascript provides us with built-in math functions.  To use them, we need to use:

 

Math.functionName(...)

 

EXAMPLE 1 – SQUARE ROOT

 

var x = 64;

var y = Math.sqrt(x);               //y will get the value 8

 

NOTE

 

You must always place Math and a dot before the function name.  Of course, to use a function, you need to know it’s name.  We will see a list of functions below.

 

EXAMPLE 2 – MAX OF TWO VALUES

 

            var a = form1.tf1.value;

            var b = form1.tf2.value;

            var c = Math.max(a,b);          //c will get the maximum value of a and b

 

EXAMPLE 3 – MINIMUM OF TWO VALUES

 

            var minimumValue = Math.min(f.tf1.value,f.tf2.value);                   //minimumValue will get the minimum value in both text fields

 

NOTE

 

When a function needs two values to do the calculations, they are both placed inside brackets separated by a comma.

 

EXAMPLE 4 – ROUNDING

 

            var r = 8.346;

            var s = Math.round(r);            //s will get the value 8

 

ALL MATH FUNCTIONS

 

Here is a list of all Math function taken from W3Schools (link).

 

 

FULLY FUNCTIONAL EXAMPLES

 

EXAMPLE 1 – SQUARE ROOT

 

Below is an example of a form that gets a number from the user and calculates the square root of that number.

 

<h1>Square Root Calculator</h1><br>

<form name="f1">

<input type="text" name="tf1">

<input type="button" name="b1" value="Square Root" onClick="f1.tf2.value = Math.sqrt(f1.tf1.value);">

<input type="text" name="tf2">

</form>

 

Click here to see this in action.

 

EXAMPLE 2 – MINIMUM VALUE

 

Below is an example of a from that gets 2 numbers from the user and calculates the minimum of the two.

 

<h1>Minimum Value Calculator</h1>

<form name="f1">

Value 1 <input type="text" name="tf1"><br>

Value 2 <input type="text" name="tf2"><br>

<input type="button" name="b1" value="Minimum" onClick="f1.tf3.value = Math.min(f1.tf1.value,f1.tf2.value);"><br>

<input type="text" name="tf3">

</form>

 

Click here to see this in action.