Wednesday, October 15, 2014

JavaScript Tutorial – Lesson 4 pt 3

JavaScript Tutorial – Lesson 4 pt 3

Contents

  1. Functions
  2. Functions with No Parameters
  3. Parameters and Return Values
  4. Functions with More Than 1 Parameter

Functions

Functions are the last bit of basic programming you need to know before you can understand and perform your own serious JavaScripting. All programming languages have functions. Functions, or subroutines, as they’re sometimes called, are bits of JavaScript that you can call over and over without having to rewrite them every time.
Let’s say you were trying to teach yourself to speed read and you wanted to sprinkle a long text with links which, when hit, would tell you the current time.
Here’s the JavaScript that does this:
01<a href="#" onClick="
02
03  var the_date = new Date();
04
05  var the_hour = the_date.getHours();
06
07  var the_minute = the_date.getMinutes();
08
09  var the_second = the_date.getSeconds();
10
11  var the_time = the_hour + ':' + the_minute + ':' + the_second;
12
13  alert('The time is now:' + the_time);">time!</a>
The details of how this little JavaScript works aren’t really important right now; I’ll go over them soon. The important thing to notice is that it’s fairly long. If you wanted to have 10 of these time links, you’d have to cut and paste this script each time, making your HTML pretty long and ugly. In addition, if you wanted to change the script, you’d have to change it in 10 different places.
Instead of having 10 copies of it on your page, you could write a function to execute the JavaScript. That way you’d have the function in one place, making it easier to edit and easier to read.
Here’s how you’d write a timer function.

Functions with No Parameters

This HTML page contains a function called announceTime(). To call announceTime from a link you’d do this:
1<a href="#" onClick="announceTime(); return false;"> time!</a>
Like so … Click here!
You saw something like this in the second lesson:
1<a href="#" onClick="alert('Hello!'); return false;"> Hello!</a>
This was calling the alert method from a link. A function is just like a method, the only difference being that a method is attached to an object. In the case of alert, the object is a Window object.
Let’s go on to the function itself. If you View Source, you’ll see the function sitting in the head of the HTML document. Here it is:
01<html>
02
03<head>
04
05<title>Function with No Parameters</title>
06
07<script langauge="JavaScript">
08
09
10
11<!-- hide me
12
13
14
15function announceTime()
16
17{
18
19  //get the date, the hour, minutes, and seconds
20
21  var the_date = new Date();
22
23  var the_hour = the_date.getHours();
24
25  var the_minute = the_date.getMinutes();
26
27  var the_second = the_date.getSeconds();
28
29
30
31  //put together the string and alert with it
32
33  var the_time = the_hour + ":" + the_minute + ":" + the_second;
34
35  alert("The time is now:" + the_time);
36
37}
38
39
40
41// show me -->
42
43
44
45</script>
46
47
48
49</head>
50
51<body>
52
53
54
55...
56
57
58
59</body>
60
61
62
63</html>
OK, let’s go over this function line by line. First, all functions come in this format:
1function functionName(parameter list)
2
3{
4
5   statements ...
6
7}
Functions’ naming rules are the same as those for variables. The first character has to be a letter or an underscore. The rest of the characters can be numbers or dashes. Also, you must make sure you don’t name a function the same as a variable. If you do, you’ll get really strange, hard to debug, results. I use internal capitalization for my function names to make sure I don’t accidentally name a function and a variable the same thing.
After the function name comes a list of parameters. This function has no parameters, so I’ll hold off describing parameters until the next example.
After the parameters comes the body of the function. This is the set of statements you want to run when the function is called. I’m going to use this timer for the next few examples, so let me describe how it works.
The first line …
1var the_date = new Date();
… gets a new date object. Just like you have to get a new array object before you can do anything with it, you need to get a new date object before you can find out what time it is. When you get a new date object, it is automatically preset to the current date and time. In order to get the information out of the object, you have to use the object’s methods:
1var the_hour = the_date.getHours(); var the_minute = the_date.getMinutes(); var the_second = the_date.getSeconds();
You might be asking yourself, how am I supposed to know what methods a date object knows? How do I even know there’s such a thing as a date object? Well, these are reasons you need to have access to a JavaScript library. I’ll do my best to explain as many of the built-in JavaScript objects as I can, but there’s no way I can go through all of them.
The rest of the function is pretty clear. It takes the numbers returned by the method calls, turns them into a string, and calls the alert method to put up a dialog box with the string. Note that you can call methods and functions from within functions. We’ll see a lot more of this.
Now, if you’ve played with the time link enough, you might have noticed something isn’t quite right. Every once in a while you get something like this:"The time is now:12:14:4". What’s the deal here?
Well, it turns out that the getSeconds() method returns a number. If it’s 12:14:04getSeconds() will return the value 4. Then when we do the string concatenation, the_minute + ":" + the_second, we get 14:4 instead of what we want. There’s an easy way out of this, and that’s to make a new function that fixes the minutes and seconds if they need fixing. This new function will demonstrate parameters and return values, two crucial parts of functions, so it deserves a page of its own.
On to parameters and return values.

Parameters and Return Values

Although functions with no parameters are pretty handy for cutting down on the amount of typing you have to do and help make your HTML look better, functions that take parameters are far more useful.
In the last example, we had a problem when the getMinutes and getSeconds methods of the Date object returned numbers less than 10. We wanted them to come out as 04 instead of just 4.
We could have done something like this:
01var the_minute = the_date.getMinutes();
02
03if (the_minute < 10)
04
05{
06
07   the_minute = "0" + the_minute;
08
09}
10
11
12
13var the_second = the_date.getSeconds();
14
15if (the_second < 10)
16
17{
18
19   the_second = "0" + the_second;
20
21}
This would work fine. Notice, however, that we’re basically writing the same code twice:If something is less than 10, stick a “0″ in front of it. When you start to notice that you’re writing almost the same exact code a bunch of times in your JavaScript, you should start thinking about writing a function to do it. In this case, I wrote a function called fixNumber:
01function fixNumber(the_number)
02
03{
04
05    if (the_number < 10)
06
07    {
08
09        the_number = "0" + the_number;
10
11    }
12
13    return the_number;
14
15}

fixNumber takes one parameter, called the_number. A parameter is just a variable that gets set when the function is called. In this case, if we call the function like this:
1var fixed_variable = fixNumber(4);
The parameter the_number gets set to 4 in the function. The body of fixNumber should make sense to you by now. It says, “if the variable the_number is less than 10, add a to the front of it.” The only new thing is the return command:return the_number. The return command is used when you say something like this:
1var some_variable = someFunction();
The variable some_variable gets set to the value returned by the someFunction() function. In fixNumber, I wrote:return the_number. This exits the function and returns the value of the_number to whatever variable is waiting to be set. So, if I write …
1var fixed_variable = fixNumber(4);
… the_number will be initially set to 4 by the function call. Then, because 4 is less than 10the_numberwill be changed to “04“. Then the_number is returned, and the variable fixed_variable will be set to “04.”
To include fixNumber in original function, announceTime(), I’ve made the following additions:
01function announceTime()
02
03{
04
05  //get the date, the hour, minutes, and seconds
06
07  var the_date = new Date();
08
09
10
11  var the_hour = the_date.getHours();
12
13  var the_minute = the_date.getMinutes();
14
15  var fixed_minute = fixNumber(the_minute);
16
17  var the_second = the_date.getSeconds();
18
19  var fixed_second = fixNumber(the_second);
20
21
22
23  //put together the string and alert with it
24
25  var the_time = the_hour + ":" + fixed_minute + ":" + fixed_second;
26
27  alert("The time is now:" +the_time);
28
29}
Let’s say it’s 12:04:05 when the time link is clicked on. We get the date using new Date(), get the hour using getHours(), which doesn’t need fixing, get the minute as we did before, which in this case will be the number 4, and then call fixNumber on the_minute:
1var fixed_minute = fixNumber(the_minute);
When fixNumber() is called, the parameter the_number gets set to the value of the_minute. In this example, since the_minute is 4the_number will be set to 4. Once the parameter is set, we go into the body of the function. Since 4 is less than 10, the_number is changed to be “04“. Then the_number is returned, using the return command. Once “04″ is returned by fixNumber, the variable fixed_minutewill equal “04″.
Once you get this working, it should look like this!
Let’s go through this step by step and then do an exercise. Assume the time is 12:04:05.
We start in function announceTime()
  1. the_minute = the_date.getMinutes(); Now the_minute = 4
  2. fixed_minute = fixNumber(the_minute); Call the fixNumber() function and return its value to fixed_minute===Now we’re in function fixNumber()===
  3. function fixNumber(the_number)fixNumber() is called with the value of the_minute, which is 4, now the_number = 4
  4. if (the_number < 10) {the_number = "0" + the_number;} Since 4 is less than 10, the_number now equals “04″
  5. return the_numberThe function exits and returns “04″ ===Function fixTime() has exited, so we’re back in announceTime()===
  6. The function returns with “04″ So fixed_minute now equals “04″

This example used a function which only had one parameter. You can actually have as many parameters as you’d like. For example, here’s a function in the Functions with More Than 1 Parameter section that takes two arrays and returns a list of elements that the arrays have in common.

Functions with More Than 1 Parameter

Here are the arrays I’ve defined:
var monkeys = new Array("mattmarg","wendy","kristin","tim","aaron", "luke"); var kittyphile = new Array("wendy", "ruby", "roscoe", "tim"); var discophile = new Array("mattmarg", "john travolta", "wendy"); var happy = new Array("tim", "wendy", "stimpy", "aaron"); var cranky = new Array("ren", "mattmarg","luke");With these arrays defined, and the arrayIntersect function written, it’s very easy to figure out which Webmonkeys love disco: dancing monkeys.
Note that even though John Travolta loves disco, he’s not on the monkeys list, so he’s not a dancing monkey. To call this function, I wrote this:
1<a href="#" onClick="arrayIntersect('dancing monkeys',monkeys,discophile); return false;">Click to see which monkeys love disco</a>
This is a function with three parameters:a string representing the name of the intersection, the first array, and the second array. It’s similarly easy to find the names of Webmonkeys who like cats:cat-loving monkeys.
Like so:
1<a href="#" onClick="arrayIntersect('monkeys who love cats',monkeys,kittyphile); return false;">Click to see the cat-loving monkeys</a>
Let’s look at the arrayIntersect function itself:
01function arrayIntersect(intersect_name, array_1, array_2)
02
03{
04
05  var the_list = "";
06
07  for (var loop_1 = 0; loop_1 < array_1.length; loop_1++)
08
09  {
10
11    for (var loop_2 = 0; loop_2 < array_2.length; loop_2++)
12
13    {
14
15      if (array_1[loop_1] == array_2[loop_2])
16
17      {
18
19        the_list = the_list + array_1[loop_1] + " ";
20
21      }
22
23    }
24
25  }
26
27  alert("the " + intersect_name + " are:"+ the_list);
28
29}
See if you can figure out for yourself what the for loops are doing in this example. The important thing to note here is the first line of the function:
1function arrayIntersect(intersect_name, array_1, array_2)
This defines a function called arrayIntersect with three parameters. Just like in the earlier example, each parameter is like a variable that gets set when the function is called. So, when this function is called like this:
1arrayIntersect('dancing monkeys',monkeys,discophile);
The following assignments are made:
  • intersect_name = ‘dancing monkeys’
  • array_1 = monkeys
  • array_2 = discophile

The only thing you have to be careful of is that you call your functions with the right number of parameters. If we had accidentally called arrayIntersect like this:
1arrayIntersect(monkeys,discophile);
We would have gotten all kinds of errors. Try it and see what happens.
Functions are the basic building blocks of any decent JavaScript, so it’s very important that you understand how they work. Here’s an exercise to test your knowledge of functions. After you’ve done the exercise, we’ll do one more exercise that combines everything we’ve learned in this lesson, and then go on to do some more work on our personal browsers. Here’s a snazzy way to give people a chance to go to another URL without having to drag their mouses all the way to the Location window:Where are you heading?
The neat thing about this script is that people can type either http://some.address.com or just some.address.com. If they do the latter, JavaScript will figure it out and append http:// to the front of what they type. Give it a try. Type www.hits.org and you’ll see that the script appends the http:// on the front.
Your assignment, of course, is to do this. You’ll need one tip though. To check the first few letters of the typed URL, you need to do this:
1var the_first_seven = the_url_they_typed.substring(0,7);
After you do this, the_first_seven will hold the first seven characters of the string typed into the prompt.
Try doing this exercise. If you give up, View Source for the solution. Try it first, though!

No comments:

Post a Comment