The address for this web page is:   `http://fishcaro.crosswinds.net/day_J6_functions.htm`
On to the next lesson!
Back to the COURSE SYLLABUS

# J6. FUNCTIONS

By creating functions, you can automate procedures that you want to use over and over again. This lesson explores how to write and use JavaScript functions.

INDEX CARD #J6:

## FUNCTIONS (J6a)

A JavaScript function is a piece of code that is defined once in a program, and can then be "called on" over and over again. A function can take any number of inputs: none, one, two, three, or more.

The code for a typical function is given below, that illustrates some basic features of JavaScript functions:

• The function name is square.
• The function takes one input (denoted here by ` x `).
• The function returns the value ` x*x = x2 `; that is, `x` squared.
• Notice that the "body" of the function must go inside braces, { }.
``` function square(x) {    return x*x; }```
This function could be written more compactly, on one line, like this:
`function square(x) { return x*x }`

## DEFINING A FUNCTION (J6b)

The example on (J6a) illustrates the following format requirements when defining a function:

the ` function ` keyword, followed by:
• the name of the function;
• an optional comma-separated list of parameter (input) names, inside parentheses;
• the JavaScript statements that make up the body of the function, contained inside curly braces.
The `return` statement causes the function to stop executing and return the value of its expression (if any) to the caller. Two sample functions are given in the following cards, together with typical "calls" to these functions.

## A TYPICAL FUNCTION (J6c)

This function takes two inputs (numbers) and returns the sum of the numbers.

``` <SCRIPT LANGUAGE="JavaScript"> function add(n1,n2) { sum = n1+n2; document.write("The sum of "+n1+" and "+n2+" is "+sum+".<BR>"); return sum; } </SCRIPT>```
Here's a typical call to the function (which must occur inside the `SCRIPT` container):

``` add(1,2); add(4.3,2.5);``` which produces this:

``` The sum of 1 and 2 is 3. The sum of 4.3 and 2.5 is 6.8.```

## A SECOND FUNCTION EXAMPLE (J6d)

```<SCRIPT LANGUAGE="JavaScript"> function dothis(str) { len=str.length; document.write("The length of "+str+" is "+len+".<BR>"); firstchar=str.charAt(0); document.write("The first character of "+str+" is "+firstchar+".<BR>"); } </SCRIPT> ``` Here's a typical call to the function (which must occur inside the `SCRIPT` container):

``` dothis("cat");```

which produces this:

``` The length of cat is 3. The first character of cat is c.```

WORKSHEET #J6:

• (WJ6.1) Write the code for the sample functions on J6c and J6d in an HTML document, within the `SCRIPT` container, and play with each function. Make some simple changes. Make lots of different calls to the function. Be sure that you understand what EVERY LINE of the code is doing before you tackle the next part of the assignment (where you'll write your OWN functions).
Write JavaScript functions to do the following:
• (WJ6.2) Take three inputs, and average them. Print out the average value (clearly labeled). Also, return the average value.
• (WJ6.3) Take two inputs (x and y) and compute x + 2y.
Have the function print out the value of x, the value of y, and the value of x + 2y (all clearly labeled).
Also, have the function RETURN the value x+2y.
• (WJ6.4) Take an input, and cube it. Call the function ` cube `. Have the function print out things like this: `23 = 8` and `(-2)3 = -8`.
Notice that if the number being cubed is POSITIVE, then you don't want parentheses in what is printed out.
However, if the number being cubed is NEGATIVE, then you DO want parentheses in what is printed out.
Test it on lots of values!
ASSIGNMENT #J6:
(AJ6.1) Please continue with the tutorial located at:
http://www.pageresource.com/jscript/index2.htm
Work through the lesson titled:
Variables, Functions, Operators, Conditionals

Some of this material is new; some is not. Make sure that you can answer all the following questions:
1. How do you declare a variable in JavaScript? Where should variable declarations go?
2. I know that, previously, you've given variables intial values without declaring them: that is, you've said things like:
`x = 5;`
`var x = 5;`
When you assign a value to a variable that you haven't declared, JavaScript automatically creates a global variable by that name for you. A global variable is one that is defined everywhere in your JavaScript code. When you write functions (which we're working with in this lesson), you usually only want a local variable; one that "disappears" once the function is finished. So, get in the good habit of declaring variables, especially when you're writing functions!
(Be able to answer these questions:
What happens when you assign a value to a variable that you haven't declared?
What is a global variable?
When you write functions, what type of variables (local or global) do you usually want?)
3. Discuss the "null" value; what is one use for it?
4. Are these variables the same, or different? Carol, CAROL, carol
5. Where should functions usually go?
6. Quickly read through the "using functions to write text in the status bar" example, but don't worry too much about it. Go on to the second part of this lesson.
7. What operators does JavaScript use for addition, subtraction, multiplication, and division?
8. The "modulus" operator is used for giving the REMAINDER:
• "5 mod 2" is the remainder when you divide 5 by 2, so "5 mod 2" is 1
• "10 mod 4" is the remainder when you divide 10 by 4, so "10 mod 4" is 2.
What operator is used in JavaScript for modulus?
9. Pull up a Netscape JavaScript Interpreter window and experiment with the modulus operator by typing in the following and studying the results. Notice that you can use a COMMA rather than the + symbol to put things together.

```var x = 5%2; document.write("the value of x is ",x,"<BR>"); ```

Replace "5%2" with 10%4, 25%7, 15%5. In each case, try to predict the result first.
10. What are the comparison operators in JavaScript?
11. Recall that the logical operators AND, OR, and NOT are defined by the following truth tables:
 A not A T F F T

 A B A AND B A OR B T T T T T F F T F T F T F F F F

The only time that "A AND B" is true, is when BOTH A and B are true.
However, "A or B" is true when AT LEAST ONE of A or B is true: when A is true, or B is true, or BOTH A and B are true.
BE ABLE TO FILL IN THESE TRUTH TABLES (given only the header rows)!
12. What symbols are used for AND, OR, and NOT (the logical operators) in JavaScript?
13. Again pull up a Netscape JavaScript Interpreter window, and verify each entry in these truth tables by using a statement like like:

```var x = true&&true; document.write("the value of x is ",x,"<BR>"); ```
Make sure that if I give you a statement like this, you can predict what will be printed out!
14. What is the form of an "if/else" statement in JavaScript? Describe how it works.
15. Write JavaScript code that compares two numbers: if they are BOTH positive, it should print out "They're both positive!". Otherwise, it should print: "At least one of the numbers is not positive." Test it on lots of values! (Hint: To do this most efficiently, you should use the logical operator AND.)
16. Write JavaScript code that compares two numbers: if at least one of the numbers is nonnegative, it should print out "At least one of the numbers is nonnegative!". Otherwise, it should print: "Both numbers are negative." Test it on lots of values! (Hint: To do this most efficiently, you should use the logical operator OR.)
17. What is the general form of a Javascript "for" loop? Be sure to explain what "condition1," "condition2," and "command" do.
18. Use a "for" loop to print out the numbers from 1 to 100, with one space between each.
19. Use a "for" loop to print out all the even numbers from 10 to 200, with a line break between each one.
20. What is the general form of a "while" statement? How does it work?
21. Use a "while" loop to print out the numbers from 1 to 100, with one space between each.
22. Use a "while" loop to print out all the even numbers from 10 to 200, with a line break between each one.
On to the next lesson!
Back to the COURSE SYLLABUS