Tuesday, July 21 st, 2014 Instructor: Craig Duckett [email protected] Functions.

85
BIT116: Scripting Lecture 05 Part 1 Tuesday, July 21 st , 2014 Instructor: Craig Duckett [email protected] Functions

Transcript of Tuesday, July 21 st, 2014 Instructor: Craig Duckett [email protected] Functions.

Page 1: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

BIT116: ScriptingLecture 05 Part 1

Tuesday, July 21st , 2014

Instructor: Craig Duckett

[email protected]

Functions

Page 2: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

2

ASSIGNMENT ANNOUNCEMENTS

REMINDER: Submit via StudentTracker. If you haven't already done so, you will need to set up a StudentTracker account in order to upload your Assignment (ZIPPED up in a single file)

Assignment 1 due on Lecture 7, Tuesday, July 28th , by midnight.

Assignment 1 Revision due on Lecture 10, Thursday, August 6th , by midnight.

Page 3: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

3

REMEMBER…

This BIT116 class is called Scripting and not Programming

One pithy way I've heard the difference between scripting and programming described is:

Scripting languages are for getting things done fast.

Programing languages are for getting something fast done ...like the ability to do scripting without having to know the intricacies of the backend programming!

Page 4: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

4

Input/Output

Page 5: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

5

Alerts and the If/Else Conditional Statement

One of the main uses of JavaScript is to provide feedback to people browsing your site. You can create an alert window that pops up and gives users the vitally important information that they need to know about your page.

We've already been working with the alert()method in some of the example pages and ICEs, but

now is the time to "officially" discuss them, as well as a quick once over of the if…else conditional statement.

Page 6: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

6

Alerts and the If/Else Conditional Statement CONTINUED

To Alert a User

This is all there is to it! Just put the text that you want to have appear within the alert() method in straight quotes.

alert("Welcome to my JavaScript page!");

In most JavaScript alert boxes, you’ll see some indication telling the user that the alert box was put up by a JavaScript command. This is a security feature to keep unscrupulous scripters from fooling hapless users. You can’t code around this. On Safari for Mac OS X, for example, it shows the URL of the site that opened the alert

Page 7: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

7

Alerts and the If/Else Conditional Statement CONTINUED

Confirming a User's Choice with confirm

While it’s useful to give information to a user, sometimes you’ll want to also get information back in return. The code below shows how to find out if the user accepts or rejects your question.

This script also introduces the idea of conditionals, which is where the script poses a test and performs different actions depending on the results of the test.

if (confirm("You sure about that?")) {alert("You said yes");

}else {

alert("You said no");}

Page 8: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

8

Alerts and the If/Else Conditional Statement CONTINUED

More About Conditionals

Conditionals break down into three parts: the if section, where we do our test; the then section, where we put the part of the script we want to do if the result is true; and an optional else section, which contains the part of the script we want to have happen if the result of the test is not true.

The contents of what we’re testing in the if section are in parentheses, and the contents of the other two sections are each contained in braces.

if (confirm("You sure about that?")) {alert("You said yes");

}else {

alert("You said no");}

Page 9: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

9

Alerts and the If/Else Conditional Statement CONTINUED

To Confirm a Choice:

1. if (confirm("Are you sure you want to do that?")) {

The confirm() method takes one parameter (the question we want to ask the user) and returns either true or false, depending on the user’s response.

2. alert("You said yes");

If the user clicked the OK button, confirm() returns true, and an alert displays, saying, “You said yes”. As you can see, this is the then section of the code, even though there’s no then operator in JavaScript. The braces serve as the delineation of the then area.

3. }

This brace ends the part that occurs when confirm() returned a value of true.

Page 10: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

10

Alerts and the If/Else Conditional Statement CONTINUED

To Confirm a Choice: CONTINUED

4. else {

Here, we begin the section that only happens when the user hits the Cancel button.

5. alert("You said no");

If the user clicked the Cancel button, confirm() returns false, and the message “You said no” is displayed.

6. }

This curly brace ends the entire if/else conditional statement.

Like Java, you can put as many statements as you wish inside the then and else braces.TIP

Page 11: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

11

Alerts and the If/Else Conditional Statement CONTINUED

There's No Right Way to Do It

There are, literally, a million ways to write any given script and still have it work correctly. For instance, braces are not required on conditionals if (and only if) there is only one statement in that code block.

In addition, there’s an alternate method of writing a conditional that takes the form:

(condition) ? truePart : falsePart;

which is the rough equivalent of:

if (condition) { truePart;}else { falsePart;}

TIP

In this class, for the most part and for clarity’s sake, I’ve included the braces in the examples and chosen to use the longer form for conditionals.

Page 12: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

12

Alerts and the If/Else Conditional Statement CONTINUED

There's No Right Way to Do It CONTINUED

That same shorthand method can also be used to set variables; for instance:

myNewVariable = (condition) ? trueValue : falseValue;

is equivalent to:

if (condition) { myNewVariable = trueValue;}else { myNewVariable = falseValue;}

There’s also no requirement that the braces have to be at the end or beginning of lines, or that the true and false code blocks need to be indented. It’s all a matter of style, and the correct style to use is the one you’ve found to work best for you.

TIP

Page 13: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

13

Prompts

Sometimes, instead of just asking a Yes/No question, you’ll want to get a more specific response. In that case, the example below allows you to ask a question (with a default answer) and receive the reply in turn.

To Prompt for a Response with prompt

1. var ans = prompt("Are you sure you want to do that?","");

Here, we’re declaring a variable (as discussed in Lecture 4). We use the var keyword to declare variables. In this case, the variable is called ans and assigned the result of the prompt(), i.e., whatever the user types into the prompt dialog.

The prompt() method is passed two pieces of information (officially called parameters), separated by a comma: the question for the user and the default answer. It returns either the user’s response or null; “null” occurs when the user hits Cancel, when there is no default and the user hits OK, or when the user clears the default answer and hits OK. For those browsers where a prompt shows a close box control, using that also returns a null result.

Page 14: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

14

Prompts CONTINUED

2. if (ans) { alert("You said " + ans); }

This conditional uses the variable that we just set. If ans exists (that is, if the user typed in a response), then the script puts up an alert window that says, “You said ” (and note the extra space at the end of that text string above) and concatenates (appends to the end) the value of ans.

3. else {alert("You refused to answer");

}

If ans is null, because the user didn’t enter anything or clicked the Cancel button in the prompt dialog, then the else block of the condition is executed, and the alert pops up.

Page 15: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

15

Var and Scope

Using var does two things:

1. It tells JavaScript to create a variable (that is, to set aside some space in memory for this new object).

2. It defines the scope of the variable, that is, where JavaScript needs to know about this particular object (remember when we talked about the difference between New York City's "Broadway" and Seattle's "Broadway"?).

If a variable is created inside a function, other functions don’t have access to it, because it’s local to that function. If it’s created outside any function, it’s global, and everything has access to it. In the above script, we created the ans global variable.

TIP

Page 16: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

16

Ultra Basic Example: Prompt() and Alert() Data Types

Page 17: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

17

Ultra Basic Example: Prompt() and Alert() with Data Types

Now that we've learned the basics of HTML form construction, we're going to backtrack for a bit and demonstrate how to use prompt() and alert() with some data types.

Afterward we'll go on to see how JavaScript can interact with some basic HTML forms (we'll return to some more advanced forms at the end of the quarter)

http://faculty.cascadia.edu/cduckett/bit116/Lecture_06/data1.html

http://faculty.cascadia.edu/cduckett/bit116/Lecture_06/data2.html

http://faculty.cascadia.edu/cduckett/bit116/Lecture_06/data1.js

http://faculty.cascadia.edu/cduckett/bit116/Lecture_06/data2.js

Page 18: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

18

Ultra Basic Example: Prompt() and Alert() with Data Types

Strict Mode

Starting with ECMAScript 5, developers are able to place their code into a more constrained form of execution known as strict mode. Strict mode improves JavaScript code by enforcing better programming practices and eliminating some of the language’s insecure and ill-advised features. Strict mode is enabled by adding the following directive to your code:

"use strict";

The “use strict”; directive can be used in two ways.

The first method of invoking strict mode is at the file level. By adding the directive at the beginning of a file (the directive may only be preceded by comments and whitespace), strict mode is enabled in a global context. This means that all of your code will be evaluated in strict mode. Caution must be taken when concatenating strict and non-strict scripts together. Placing a strict script first will force the non-strict script to be evaluated in strict mode. Placing a non-strict script first will cause the opposite behavior. This caused some problems for Amazon.

Page 19: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

19

Ultra Basic Example: Prompt() and Alert() with Data Types

Strict Mode CONTINUED

The second way to enable strict mode is at the function level. To enable this level of strict mode, place the “use strict”; directive at the beginning of the function body. As with global strict mode, the directive may only be preceded by whitespace and comments. Using strict mode at the function level allows a programmer to mix and match strict and non-strict functions in the same file. This is useful when some legacy code relies on features that have been deprecated in strict mode. The following example shows how strict and non-strict functions can coexist in a single file.

function foo() { "use strict"; // this function is executed in strict mode}

function bar() { // this function is executed in non-strict mode}

One of the nice things about strict mode is its backward compatibility. Older versions of JavaScript will treat the “use strict”; directive as a meaningless string literal and ignore it. However, newer versions of JavaScript will give the statement special treatment and switch to strict mode.

Page 20: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

20

Ultra Basic Example: Prompt() and Alert() with Data Types

Strict Mode CONTINUED

JavaScript has an interesting way of handling variable declarations. Variables that are not declared using the var keyword are implied to be global variables. The following piece of code uses three variables: x, y, and z.

function foo() { var x; var z;

x = 1; y = 2; z = x + y;}

Notice that only the variables ‘x’ and ‘z’ are declared using the var keyword. There is a good chance that the programmer also meant to declare ‘y’, but mistakenly did not. The code will execute properly, but with the side effect of creating a global variable named ‘y’ with the value 2. Since window is the global object, this is equivalent to writing: window.y = 2;

Page 21: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

21

Ultra Basic Example: Prompt() and Alert() with Data Types

Strict Mode CONTINUED

This behavior can be problematic if ‘y’ is already defined elsewhere and is expected to have a different value.

This leads to code that doesn’t scale well and is difficult to debug. Enabling strict mode will catch this problem.

Instead of making ‘y’ a global variable, an exception will occur.

The exception shown in the browser might look like this:

ReferenceError: y is not defined

Page 22: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

22

Functions

Page 23: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

23

Functions: What is a Function?

A function is basically a little script within a larger script. Its purpose is to perform a single task or a series of tasks. What a function does depends on what code you place inside it. For instance, a function might write a line of text to the browser or calculate a numeric value and return that value to the main script.

As you may recall from math class, a function can be used to calculate values on a coordinate plane. You may have seen calculations like these:

f(x) = x + 2y = x + 2

Both are commonly used to calculate the y coordinate from the value of the x coordinate. If you need the y coordinate when x is equal to 3, you substitute 3 for x to get the y value: 3 + 2=5. Using the function, you find that when x = 3, y = 5. The function itself is just sitting on the paper (or, in our case, the script) until you need to use it to perform its task. And you can use the function as many times as you need to, by calling it from the main script.

Page 24: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

24

Functions: Why Functions Are Useful

Functions help organize the various parts of a script into the different tasks that must be accomplished. By using one function for writing text and another for making a calculation, you make it easier for yourself and others to see the purpose of each section of the script, and thus debug it more easily.

Another reason functions are useful is their reusability. They can be used more than once within a script to perform their task. Rather than rewriting the entire block of code, you can simply call the function again.

Consider the simple function y = x +2 . If you use it only once, the function doesn’t serve much purpose. If you need to get several values, however, the function becomes increasingly useful. Rather than writing out the formula for each calculation, you can just substitute the x values each time you need to get the y value. So, if you need the y value when x is 3, 4, and 5, you can use the function three times to get the y values. Instead of writing the content of the function three times, it only needs to be written once to get three answers.

Functions can perform complex tasks and can be quite lengthy. In the examples in this and later lectures, you’ll see just how useful and time-saving they are in JavaScript.

Page 25: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

25

Functions: Structuring Functions

Now that you understand what functions are and why you want to use them, you need to learn how to structure them in your scripts.

A function needs to be declared with its name and its code.

There are also some optional additions you can use to make functions even more useful.

You can import one or more variables into the function, which are called parameters.

You can also return a value to the main script from the function using the return statement.

Page 26: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

26

Declaring Functions

Page 27: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

27

Functions: Declaring Functions

On the first line of a function, you declare it as a function, name it, and indicate whether it accepts any parameters.

To declare a function, you use the reserved word function, followed by its name, and then a set of parentheses:

function functionName()

The reserved word function tells the browser that you are declaring a function and that more information will follow.

The next piece of information is the function’s name.

After that, the set of parentheses indicates whether the function accepts any parameters.

Page 28: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

28

Functions: Declaring Functions CONTINUED

For example, to name your function reallyGroovy and indicate that it does not use any parameters, the first line looks like this:

function reallyGroovy()

Because the function does not use any parameters, the parentheses are left empty. As with variable names, there are some special considerations for naming functions. You’ll learn about those considerations after the discussion of the function structure.

You may have noticed that this line does not end with a semicolon, as other code lines you’ve seen in this class. The semicolon is absent because you use a different technique to show where the function’s code begins and ends, as described next.

However, each of the separate lines of code within the function does end with a semicolon, as you willsee in the examples in this lecture.

Page 29: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

29

Functions: Defining the Code for Functions

Curly brackets { } (or "squiggles" as I like to call them) surround the code inside the function.

The opening curly bracket marks the beginning of the function’s code; then comes the code; and, finally, the closing curly bracket marks the end of the function, in this format:

function reallyGroovy(){

//JavaScript code here}

The browser will execute all of the code inside the curly brackets when the function is called (as you will learn later in this lecture).

When the browser gets to the closing curly bracket, it knows the function has ended. The browser will move to the next line of code or continue whatever it was doing before the function was called.

Page 30: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

30

Defining the Code for Functions

Page 31: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

31

Functions: Defining the Code for Functions CONTINUED

You have some flexibility in formatting the curly brackets. There are several common ways to place the curly brackets into a script.

The format shown in the this example “lines up” the brackets so that the opening and closing of the function are seen on the left margin of the code.

function reallyGroovy(){

//JavaScript code here}

This method is handy if you use other statements that need curly brackets.

By indenting each set of brackets, you make it easy to see which brackets are nested within the function and which ones begin and end the function itself.

Page 32: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

32

Functions: Defining the Code for Functions CONTINUED

Another common format is to put the opening bracket on the same line as the function declaration, rather than on the next line:

function reallyGroovy() { // JavaScript code here}

In this format, the opening brackets of code blocks are seen to the right, and closing brackets appear on the left. This can be a useful technique if you wish to count how many brackets have been opened and/or closed within a segment of code.

Of course, if you have a particularly short function, you can even place the entirety of the function on a single line, like this:

function reallyGroovy() { //JavaScript code here }

Page 33: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

33

Functions: Defining the Code for Functions CONTINUED

The curly brackets are flexible in this way because white space, tabs, and line breaks that appear between tokens in JavaScript are ignored (tokens are such things as variable or function names, keywords, or other parts of the code that must remain intact).

Thus, the following code would be valid:

function reallyGroovy() {var

a=

5; var b = 3; var c = 6; }

Though it may be more difficult to read, JavaScript will still see it as valid code since the proper syntax is otherwise in place.

The format you choose for the curly brackets will likely depend on your background in programming and how you like to see the code… or your company likes to see the code!

Page 34: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

34

Functions: Naming Functions

As with variables, functions need to be named carefully to avoid problems with your scripts.

The same basic rules that applied to variables apply to the naming of functions: case sensitivity, using allowed characters, avoiding reserved words, and giving functions memorable and meaningful names.

Using Case in Function Names

Function names are case sensitive, just like variable names. This means that reallyGroovy, REALLYGROOVY, ReallyGroovy, and reallygroovy represent four different functions!

Remember that you need to call your functions using the same letter cases as you used in their declarations.

Page 35: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

35

Naming Functions

Page 36: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

36

Functions: Naming Functions CONTINUED

Using Allowed Characters and Avoiding Reserved Words

The characters that are allowed for function names are the same as those you can use for variable names:

• The function name must begin with a letter or an underscore character ( _ ).• The function name cannot contain any spaces.• The function name cannot use JavaScript reserved words for function names. Doing so can cause the

function to fail, which can cause real problems within a script.

Page 37: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

37

Functions: Naming Functions CONTINUED

Giving Functions Meaningful Names

Your functions will be easier to remember and to debug if you choose names that reflect their purpose. You should use a name that represents its value, such as salesTax to stand for the number of an example on a page. A function name should tell you something about what the function will do. For example, suppose that you create a function that writes some text to the page. It could contain the following line of code:

document.write("<strong>Lorem ipsum dolor sit amet!</strong>");

You could just name the function text, but that might not be descriptive enough, because you could have other functions that also write text to the page. Instead, you might name it something like strongText, so that you know that the function is used to print a piece of strongly emphasized text to the browser.

function strongText() {document.write("<strong>Lorem ipsum dolor sit

amet!</strong>");}

Page 38: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

38

Adding Parameters to Functions

Page 39: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

39

Functions: Adding Parameters to Functions

Parameters are used to allow a function to import one or more values from somewhere outside the function. Parameters are set on the first line of the function inside the set of parentheses, in this format:

function functionName(variable1,variable2)

Any value brought in as a parameter becomes a variable within the function, using the name you give it inside the parentheses.

For example, here is how you would define a function reallyGroovy with the parameters (variables) groovyCar and groovyHouse:

function reallyGroovy(groovyCar, groovyHouse) {// JavaScript code here

}

NOTE: Notice that in JavaScript, you do not use the var keyword when you set the parameters for a function. JavaScript declares the variables automatically when they are set as parameters to a function, so the var keyword is not needed here.

Page 40: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

40

Functions: Adding Parameters to Functions CONTINUED

Using Function Parameter Values

When you assign parameters to a function, you can use them like any other variables.

For example, you could give groovyCar and groovyHouse variables value to other variables inside the function by using the assignment operator:

function reallyGroovy(groovyCar, groovyHouse) {var myCar = groovyCar;var myHouse = groovyHouse;

}

This assigns the value of the groovyCar parameter to a variable named myCar, and the value groovyHouse to myHouse.

Page 41: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

41

Functions: Adding Parameters to Functions CONTINUED

Instead of assigning their values to other variables, you could just use the groovyCar and groovyHouse parameters:

function reallyGroovy(groovyCar, groovyHouse) {document.write("My groovy ride is a " + groovyCar + ".<br>");document.write("My groovy abode is an " + groovyHouse + ".");

}

If the value of groovyCar is Pinto and the value of groovyHouse is igloo, then the function would print this to the browser when it is called:

My groovy ride is a Pinto.My groovy abode is an igloo.

NOTE: The groovyCar and groovyHouse parameters are given values out of the blue here for example purposes. In actual use, the values must come from somewhere in the main script or another function, or else the variables will have no values.

Page 42: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

42

Functions: Adding Return Statements to Functions

A return statement is used to be sure that a function returns a specific value to the main script, to be used in the main script. You place the return statement as the last line of the function before the closing curly bracket and end it with a semicolon.

Most often, the value returned is the value of a variable, using the following format:

return variableName;

For example, to return the value of a variable groovyText, the return statement looks like this:

return groovyText;

This returns the value of groovyText to the place in the main script where the function was called.

Page 43: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

43

Adding Return Statements to Functions

Page 44: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

44

Functions: Adding Return Statements to Functions CONTINUED

Suppose that you want to write a function that returns the result of adding two strings together. You could use a return statement, as in this example:

function getGroovyText() {var groovy1 = "JavaScript is ";var groovy2 = "groovy!";var groovyText = groovy1 + groovy2;return groovyText;

}

In this function, the first two variables are assigned string values, and the groovyText variable is given the value of the addition of those two strings. The new value is sent back to the script where it was called. It returns this string:

JavaScript is groovy!

This returned value is then used in the main script.

NOTE: In its current form, this function is not very useful, because the strings were just defined in the function rather than being brought in as parameters.

Page 45: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

45

Functions: Adding Return Statements to Functions CONTINUED

In addition to returning a variable value, you can return a simple value or even nothing. All of the following would be valid return statements:

return "This is cool"; // Returns a string valuereturn 42; // Returns a numeric valuereturn true; // Returns a Boolean valuereturn null; // Returns a null valuereturn; // Returns nothing

All of these return the control back to the first JavaScript statement after the function call. Returning nothing does this without sending back a value.

You can also return an expression, such as the addition of numbers or strings (or any other expression you decide to build). The following would also be valid return statements:

Return "This is " + "groovy!"; // Returns concatenated stringsreturn 21 + 20 + 1; // Returns total of the three added numbers

These would return the values “This is groovy!” and 42, respectively.

Page 46: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

46

Calling Functions

Page 47: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

47

Functions: Calling Functions in Scripts

Now that you know how the function itself works, you need to learn how to call a function in your script. A call to a function in JavaScript is simply the function name along with the set of parentheses (with or without parameters between the opening and closing parentheses), ending with a semicolon, like a normal JavaScript statement:

functionName();

You can call functions anywhere in your script code. You can even call a function inside of another function. A good rule to follow is to have the function definition come before the function call in the script. The easiest way to be sure that your function definition comes before your function call is to place all of your function definitions as close to the beginning of the script as possible.

NOTE: Defining a function before calling it is a suggestion for good coding practice, not a strict rule. A function can be called anywhere in JavaScript, but the function code must be loaded by the browser before the function will work. This is why it is suggested that you define your functions before calling them. If you were to call a function that is defined near the bottom of a script, there is a chance it would not load in time to be executed. Thus, it is normally best to define a function before it is called.

Page 48: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

48

Functions: Script Tags (Head or Body)

When adding scripts directly to a web page rather than using an external file, making sure that variable and function declarations are in the head section often helps to ensure they are available when the script calls them in the body section.

However, since JavaScript often uses information from the document that may not have loaded yet, this could become problematic.

On the other hand, having a lot of JavaScript code in the body section can also be troublesome when you need to edit your HTML code (and if the JavaScript code is in the body section it needs to be after the element(s) that have the information JavaScript needs to use to ensure the necessary information is loaded).

It is preferable to place all of your code into an external JavaScript file.

For purposes of this class, many of my files will use internal Javascript in the head for demonstration purposes (easier to demonstrate code with only one file open rather than two).

Page 49: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

49

Creating an Alert

Page 50: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

50

Functions: Creating an Alert

Rather than writing something to the screen with the document.write() method, you can create a JavaScript alert that pops up in a message box by using the window.alert method.

Like the document.write() method, the window.alert method takes the text string for the alert as a parameter, using this format:

window.alert("alert_text");or just

alert("alert_text");

The string of text will be displayed in the alert pop-up box.

For example, suppose that you want to display “This is an alert!” in the pop-up box. You would write the command like this:

alert("This is an alert!");

Page 51: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

51

Functions: Using a Function for an Alert

The following code uses a function to pop up an alert box.

function showMessage() {alert("This is an alert!");

}

showMessage();

This example creates a function named showMessage() to do the job of showing the alert.

The alert will be shown only if you call the showMessage() function somewhere after it is defined.

In this case, the function is called right after its definition. The result is a small alert box with the message “This is an alert!”

NOTE: Even though the function is defined first, it doesn’t mean it will be executed first. A function is not executed until it is called; in other words, JavaScript will not use the function until it gets to the function call in the script.

Page 52: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

52

Calling a Function from Another Function

Page 53: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

53

Functions: Calling a Function from Another Function

Calling a function within another function can be a useful way to organize the sequence in which your events will occur.

Usually, the function is placed inside another function that has a larger task to finish.

When you place a function call within a function, you should define the function that will be called before you define the function that calls it, per the earlier suggestion that a function should be defined before it is called.

Page 54: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

54

Functions: Calling a Function from Another Function CONTINUED

Here is an example of two functions, where the second function calls the first one:

function updateAlert(){window.alert("Welcome! This site is updated daily!");

}

function callAlert() {updateAlert();

}

callAlert();

Notice that the updateAlert() function is where all the real action happens. Everything else is a function call. The callAlert() function does nothing more than call the updateAlert() function so that it is executed. Finally, you see the command that starts the entire sequence, which is the call to the callAlert() function. Since this is the first JavaScript statement outside a function, it is executed first. When it is executed, it just calls the updateAlert() function, which does the work of displaying the alert.

Page 55: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

55

Functions: Calling a Function from Another Function CONTINUED

Now suppose that you want to create three functions to perform three tasks. To make sure that they occur in the correct sequence, you can call them in order from within another function. Here is an example:

function updateAlert() {alert("Welcome! This site is updated daily!");

}

function sectionAlert() {alert("Please visit the picture section!");

}

function linksAlert() {alert("Also, check out my links page!");

}

function getMessages() {updateAlert();sectionAlert();linksAlert();

}

getMessages();

NOTE: Creating a script that pops up message after message is not something you typically want to do. Although the example demonstrates the correct use of function calls, a script that does this would likely annoy your viewers!

Page 56: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

56

Calling Functions with Parameters

Page 57: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

57

Functions: Calling Functions with Parameters

The previous example used three different functions to show three alerts. Although it works, it would be nice if you did not need to write a new function for each alert. You can avoid doing this by using parameters.

You can create a function to be used multiple times to do the same thing, but with the new information from the parameters each time.

As mentioned earlier, variables are commonly used as parameters. However, you can also use a value as a parameter.

You’ll learn about the different types of variable parameters first, and then take a look at value parameters.

If you want to send the values of certain variables to the function, you must first declare the variables and then be sure that they have the values you need before you send them. Here, the scope of a variable becomes important. The scope of a variable determines where it is and is not valid.

JavaScript has global and local variables.

Page 58: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

58

Global Variables

Page 59: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

59

Functions: Global Variables

Global variables are the variables that are defined outside any functions, and they can be changed anywhere in the script—whether inside or outside of functions. These are like "instance variables" in Java.

A global variable is declared anywhere outside a function, as in the following code:

var myCar="Nissan Rogue";var myPaycheck="2000";

The variables in this example can be changed anywhere in the script.

This also means that they can even be accidentally overwritten or changed by a function!

Page 60: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

60

Functions: Global Variables CONTINUED

To understand how global variables can be affected by a function, consider an example that shows two alerts.

You want one alert to tell you how much money you need to get a certain car, and you want the other one to tell you how much money you currently have and what type of car you now own. What would happen if you used the following code?

var myCar = "Nissan Rogue";var myPaycheck = 2000;

function newCar() {myCar = "Ferrari";myPaycheck = 4000;window.alert("You need $" + myPaycheck + " to get a " +

myCar);}

newCar();

window.alert("You make $" + myPaycheck + " and have a " + myCar);

Page 61: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

61

Functions: Global Variables CONTINUED

It may look as if you created new variables inside the function, even though they had the same name. However, the script would output the following text in the two alerts:

You need $4000 to get a FerrariYou make $4000 and have a Ferrari

Obviously, this isn’t right.

This example demonstrates why you need to use the var keyword when declaring variables. Without the var keyword, you are not creating new variables inside the function (which would make them local). Instead, you are changing the value of your global variables—you are issuing a reassignment command rather than a new variable command.

To clear this up, you need to either change one set of variable names or use local variables (as described in the next section).

Page 62: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

62

Local Variables

Page 63: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

63

Functions: Local Variables

A local variable can be used only within the function in which it is declared. It does not exist outside that function, unless you pass it along to another function by using a parameter.

The key to creating a local variable in a function is to be sure that you declare it using the var keyword. Otherwise, any global variables by that name could be changed, as you saw in the previous example.

To declare a local variable, you must place it inside a function and use the var keyword, as shown in this code:

function newCar() {var myCar="Ferrari";var myPaycheck="4000";

}

The myCar and myPaycheck variables are now local variables, which can only be seen and changed by the newCar() function.

Page 64: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

64

Functions: Local Variables CONTINUED

To correct the script in the previous section, you just need to add the var keyword to declare the local variables inside the function:

var myCar = "Nissan Rogue";var myPaycheck = 2000;

function newCar() {var myCar = "Ferrari"; // var added, makes this myCar localvar myPaycheck = 4000; // var added, makes this myPaycheck

localwindow.alert("You need $" + myPaycheck + " to get a " +

myCar);}

newCar();

window.alert("You make $" + myPaycheck + " and have a " + myCar);

Now the alerts should appear as you intended:

You need $4000 to get a FerrariYou make $2000 and have a Nissan Rogue

Page 65: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

65

Using Variables as Function Parameters

Page 66: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

66

Functions: Using Variables as Function Parameters

The following example uses variable parameters. It sends a global variable along to the function. It then assigns its value to a local variable to avoid any accidental changes.

function checkAlert(myPaycheck) {var pcheck = myPaycheck;alert("You make $" + pcheck);

}var myPaycheck = 2000;checkAlert(myPaycheck);

The script begins with the checkAlert() function, which takes in the parameter myPaycheck. The line of code in the function assigns the value of paycheck to a local variable, pcheck. This way, you can use pcheck within the function to avoid changing the global myPaycheck variable.

The function is then used to display an alert that uses the value of pcheck. After the function, in the outside script, the global variable paycheck is assigned a value of 2000. Then the code calls the checkAlert() function and sends it the value of the myPaycheck variable.

Page 67: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

67

Functions: Using Variables as Function Parameters CONTINUED

The previous example shows a rather long way to keep from changing a global variable.

Since function parameters are sent as values of variables, you can change the variable name the function accepts inside the parentheses in the function definition. This creates a local variable from the parameter that is sent to the function.

Here is an example:

function checkAlert(pcheck) {alert("You make $" + pcheck);

}var myPaycheck = 2000;checkAlert(myPaycheck);

When this code calls the checkAlert() function, it sends that function the value of the myPaycheck variable. The value is pulled in from the function itself. Rather than naming the value “myPaycheck” here and assigning it to another variable, you simply use another name within the parentheses: pcheck. The pcheck variable becomes a local variable inside the checkAlert() function. Since the code sends myPaycheck a value of 2000, pcheck will be 2000, unless you change it later in the function.

Page 68: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

68

Using Value Parameters

Page 69: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

69

Functions: Using Value Parameters

You can also send a value as a parameter directly. Instead of needing to declare a global variable in order to send a parameter, you can just send a value that will be turned into a local variable inside the function. This allows you to send a value on the fly and eliminates the need to have a global variable handy.

For example, the last example in the previous section can be modified to add more information while using one less line by using value parameters:

function checkAlert(pcheck, myCar) {alert("You make $" + pcheck + " and have a " + myCar);

}checkAlert(2000,"Nissan Rogue");

In this example, the function call sends two parameters to the function. The first one is a numeric value and does not need quotes. The second value is a string and needs to be enclosed in quotes. These values are then sent to the function, where they are read in as the local variables pcheck and myCar, respectively. They can now be used in the function to display this sentence in an alert:

You make $2000 and have a Nissan Rogue

Page 70: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

70

Functions: Using Value Parameters CONTINUED

Parameters can also be sent using expressions, such as the following:

checkAlert(1500 + 500, "Nissan " + "Rogue");

JavaScript will evaluate each expression and send the results as parameters to the function.

Thus, the preceding code would have the same end result (adding 1500 and 500 gives 2000, and adding “Nissan ” and “Rogue” gives “Nissan Rogue”):

You make $2000 and have a Nissan Rogue

Page 71: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

71

Functions: Parameters are Optional

Another thing that should be mentioned is that sending parameters to a function is optional.

The function will do its best to do its work without the parameter values that are not sent.

You could call the function checkAlert() without any parameters:

function checkAlert(pcheck,myCar) {window.alert("You make $" + pcheck + " and have a " + myCar);

}checkAlert();

Your result would be something like the following text:

You make $undefined and have a undefined

Thus, it is a good idea to set up some code to handle a situation where a parameter is not sent.

This can be done using conditionals.

Page 72: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

72

Functions: Parameters are Optional CONTINUED

Here is one way to check if the parameters were sent to checkAlert():

function checkAlert(pcheck,myCar) {if (pcheck && myCar) {

alert("You make $" + pcheck + " and have a " + myCar);}else {

alert("My parameters are missing!");}

}

checkAlert();

This essentially tells JavaScript to see if the parameters exist before writing the statement to the page. If they do exist, the statement is written on the page with the parameter values. If they do not exist, then the viewer gets an alert that says “My parameters are missing!”

Page 73: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

73

Calling Functions with Return Statements

Page 74: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

74

Functions: Calling Functions with Return Statements

To call a function and use a return statement in the function, you can assign the result of the function to a variable.

In this way, the variable gets the value returned from the function and can be used later in the script.

This is the format for declaring a variable that has the value returned by a function:

var variableName = functionName();

Page 75: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

75

Functions: Calling Functions with Return Statements CONTINUED

Consider the previous example, which had a function that returned the value of two text strings added together. You can modify it so that the function result is assigned to a variable, as follows:

function getGroovyText() {var groovy1 = "JavaScript is ";var groovy2 = "groovy!";var groovyText = groovy1 + groovy2;return groovyText;

}var alertText = getGroovyText();alert(alertText);

As you can see, the function returns the value of the added text variable to the script.

By assigning the result of the getGroovyText() function to the alertText variable, you can use the added text later in the script. The variable is used to send an alert to the user with the result of the added text. The alert message reads:

JavaScript is groovy!

Page 76: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

76

Other Ways to Define Functions

Page 77: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

77

Functions: Other Ways to Define Functions

There are several ways to define functions that you may come across while looking at scripts or may find useful in coding new scripts:

• the function declaration (already discussed)• the function constructor• the function expression

Page 78: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

78

Functions: Other Ways to Define Functions CONTINUED

The Function Declaration

This is the method you have been using up to this point and one that will be used often in this class.

As you will recall, you simply declare the function as follows:

function functionName() {//Code for function here

}

You can also add parameters and/or return statements as mentioned earlier in this lecture.

Page 79: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

79

Functions: Other Ways to Define Functions CONTINUED

The Function Constructor

The function constructor creates a function object in the same way you would create a new instance of an object (Objects will be discussed in much greater detail in Lecture 7 to coincide with the reading in Chapter 8 of the Pollock book):

var functionName = new Function (arguments, code for function) ;

This will work like other functions, but the main drawback to this method is that it has poorer performance than the other methods (it is evaluated every time it is used rather than only being parsed once).

More often than not, you will use one of the other two methods for defining functions.

Page 80: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

80

Functions: Other Ways to Define Functions CONTINUED

The Function Expression

The function expression (also called the function operator) uses the same syntax as a function declaration. The main difference between this and a function declaration is that a function declaration creates a variable with the same name as the function name that can be used outside the function, while the function expression can only access the variable by its name within the function itself. For instance, the following code uses a function declaration and can output an alert using the function name as a variable:

function sendAlert() {var myNum = 1;

}alert(sendAlert);

On the other hand, the following code would give an error when run:

var getFunc = function sendAlert() {var myNum = 1;

}alert(sendAlert); // You have to pass getFunc, not sendAlert

Page 81: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

81

Anonymous Functions

Page 82: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

82

Functions: Other Ways to Define Functions CONTINUED

Anonymous Functions

One effective use of the function expression is to use it without a function name to create an anonymous function.

An anonymous function is one that is created and called at the same time, and is helpful when you wish to call a function in only one place in your code (rather than declaring the function elsewhere in the code and reusing it by calling it more than once).

The following is the general format for an anonymous function:

var varName = function(parameters) {// Code for function

}; // <-- Notice the use of the semi-colon here

This uses the function keyword but does not name the function.

Page 83: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

83

Functions: Other Ways to Define Functions CONTINUED

Anonymous Functions CONTINUED

Anonymous functions are quite useful when dealing with JavaScript events.

For example, to react to a user clicking the mouse while on a Web page, you could write a simple function for a click event on the document and then call it, as in the following code:

function doNotClick() {alert("Do not click on my page!");

}onclick = doNotClick;

This declares the function, then calls it afterward (without parentheses) to handle the click event.

Page 84: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

84

Functions: Other Ways to Define Functions CONTINUED

Anonymous Functions CONTINUED

You could combine these two steps into one using an anonymous function, as follows:

onclick = function() {alert("Do not click on my page!");

};

Since the reaction to this event will only be in one place in the JavaScript code, the anonymous function is a handy way to handle the event without the need to declare the function elsewhere and then call it.

This technique and the type of code used for event handling (such as in the code listings above) will be discussed in more detail in Lecture 14 (and in the reading for Chapter 10 of the Pollock book)

Page 85: Tuesday, July 21 st, 2014 Instructor: Craig Duckett cduckett@cascadia.edu Functions.

85

Please begin working on the LECTURE 5 In-Class Exercises.

When you have completed your ICE, call the Instructor over to verify your work. If you have questions about your work, please call over the Instructor to clarify.

Once you have completed your ICEs, you are free to go for the day.

If you don't finish your ICEs by the end of class, you will still get full credit for actively doing the work, but it is greatly recommended you finish any outstanding ICEs outside of class.

ICE 05 Part 1