JavaScript Chapter 4 Arrays and Functions

Javascript Arrays

A normalJavascript variable like var age = 18 holds a single piece of data. An array is a way to hold more than one piece of data under the same name. There's a few ways to set up an array but the simplest looks like this:
var my_array = [10, "ten", true];
This sets up an array to hold three values all under the single variable name we called my_array. Notice that you can store numbers, strings of text, and Boolean values in an array. Each value needs to be separated by a comma. The values need to go between two square brackets and after an equal sign.

To get at the values in your array you use something called the index value. This is a number between square brackets. The number corresponds to a value's position in the array (position numbers start at 0):
So my_array[0] will hold the value 10, my_array[1] will hold the text "ten", and my_array[2] will hold the Boolean value true. You could then write the values to a web page:
document.write( my_array[0] + "<BR>");
document.write( my_array[1] + "<BR>");
document.write( my_array[2] + "<BR>");
Test it out with the following script:
Code for a simple Javascript array
Run the script in a browser and you should see the number 10 displayed. Now change the 0 in between the square brackets of my_array[0] to a 1. Save the change and refresh. The text "ten" will be written out. Change the 1 into a 2 and you'll see "true" displayed.
Now change the 2 into a 3. This time the word "undefined" will display. The reason is because you only set up your array to hold 3 items. When you typed a 3 instead of a 2 you were trying to access item number 4 (0 to 3, remember). But you haven't defined a fourth item. Even though you haven't got a fourth item, Javascript doesn't throw you up an error, it doesn't refuse to work. Instead, it adds a new position to the end of your array. You can even store something in this new position. Change your script to this (the new parts are in bold):
var my_array = [10, "ten", true];
document.write( my_array[3] + "<BR>");
my_array[3] ="new item";
document.write( my_array[3] );
Javascript first prints out "undefined" then "new item".
Notice the way we're assigning this new value:
my_array[3] ="new item";
On the left of the equal sign, we have the name of the array then a pair of square brackets. Inside of the square brackets is the array position number we want to access. After the equal sign you type the value you want to assign. So it's just like normal variable assignment except you add the square brackets and the array position after the variable name.
Another way to set up an array is with the new keyword:
var my_array = new Array( );
This time after the equal sign we have the word new then a space. The word Array comes next (uppercase A and never lowercase). Immediately after the word Array you need a pair of round brackets. If you like you can add how many positions the array is going to hold:
var my_array = new Array(3);
This says "set up an array with 3 positions". You don't have to add any array positions, though. It's up to you.
However, when you're assigning values to each position you do need to add the index positions. You do it like this:
var my_array = new Array( );
my_array[0] = 10;
my_array[1] = "ten";
my_array[2] = true;
So the first line sets up an array called my_array. The next three lines assign values to each position in the new array. The method above is the one we'll use to set up an array from now on.

Arrays and Loops

Arrays are quite often used with loops. That's because the index position of arrays are numbers that you swap for the loop variable. As an example, study the following code (of course, you can try it out as well):
var counter = 0;
var lottery_numbers = new Array();
while ( counter < 49 ) {
lottery_numbers[counter] = counter + 1;
document.write( lottery_numbers[counter] + "<BR>" );
What the script does is to assign values to an array called lottery_numbers. We've used a while loop. The loop goes round and round executing this line:
lottery_numbers[counter] = counter + 1;
Instead of saying lottery_numbers[0]lottery_numbers[1]lottery_numbers[2], etc, we've replaced the index number with the variable name counter. We can do this because counter changes each time round the loop. Javascript knows what's in the counter variable and uses this as the index. After the equal sign, we're assigning whatever is in the counter variable (plus 1) to each position in the array. (Can you see why we'd need to add 1?)

There's a lot more you can do with arrays,

Javascript Functions

The scripts we have at the moment are set to run as soon as the page loads in the browser. But they don't have to. A better way is to put the code inside something called a function. A function is just a separate code segment that you call into action. In fact, they don't do anything unless you do call them into action. Let's see how they work.

A function without any code looks like this:
function myFunction() {
You start with the word function (lowercase "f"). After a space you type a name for your function. Function names are just like variable names in that you can call them anything you like. But they can't start with a number; you can't have spaces in the name; and the variable should contain only letters, numbers ( but not the first character of the variable), a dollar sign ($) or an underscore ( _ ).
After your function name you need a pair of round brackets. The round brackets are for something called arguments, which we'll get to shortly.
Finally, you need a pair of curly brackets. Any code you want to execute goes between the two curly brackets.
You don't need to spread your functions out over multiple lines, however. This is perfectly valid:
function myFunction() { alert("My Function"); }
But your code will be easier to read if your functions aren't all on one line.
To test functions out, create a new web page. You can use the template you created in an earlier section. In between two SCRIPT tags, add the following:
function myFunction( ) {
alert( "My Function" );
Your web page code should look like this:
An example of a function in Javascript
Now load your web page into a browser. You should find that nothing happens: the alert between the two curly brackets of the function doesn't display.
The reason the alert doesn't display is because the function hasn't been called into action. There are lots of ways to call a function. One way is via the onLoad event of the browser window. So add this to the BODY section of you HTML:
<BODY onLoad = "myFunction()">
After the word onLoad we have an equal sign (it doesn't have to be capital "L", by the way - we've done it like this for readability's sake). This is followed by the name of the function we created, the one we want to call. The name of the function is best placed between double or single quotes because some browsers won't work without quotes surrounding your function name. As well as the function name, you need the round brackets.
Save your changes and refresh the page in your browser. You should find that the alert box now displays - the function has been called into action!

Functions calling other functions

One function can also call another into action. You don't want one giant function that does everything, so the standard practice is to have lots of smaller ones doing specific things. Suppose you had a function that gets values from a form when a button is clicked. You may then want to set up other functions that check things like an email text box to see if the address is valid, or to see if a check box has been ticked. The point is that breaking your code down into separate segments that do specific jobs (functions) makes life easier for you as a coder.
As a simple example of one function that calls another, take a look at the following code:
One Javascript function calling another
So we've added a second function to the code we had before. This is the function we've added:
function secondFunction() {
alert("My Second Function");
The code between the curly brackets of the function is just an alert box. Now have a look at the first function:
function myFunction() {
We no longer have the alert box inside the first function. What we have is this:
To call a function into action, then, all you need to do is to type the function name, and its round brackets, ending the line with a semicolon.
Try it out for yourself. When you load the page in a browser, the BODY onLoad call is the first thing to happen. This activates myFunction. When myFunction gets executed, it calls secondFunction into action.

Return values

Quite often, you'll want to get something back from your functions. If you're examining an email address for errors, you'd want to get back the results from your code (is it a valid email address or not). Or if you have a check box asking user to agree to your terms and conditions, you'd want the answer back from your function. This value that you want to get back is called the return value in Javascript. The return value can be a string of text, a number, a Boolean value, or even objects. But they only return one value. Let's adapt our second function so that it returns a value.
function secondFunction() {
var alertString = "My Return Value";
return alertString;
In this simple example, we've set up a variable called alertString. We've set this value to be the text "My Return Value". To get this value out of the function, we have this line:
return alertString;
To get a value out, you type the word return followed by a space (not an equal sign). Next you type the variable name or the value (true or false, for example) that you want to get back. For us, this was the variable called alertString.
But we need to adapt the first function to get at this value. Study this new version of the first function:
function myFunction() {
var retVal = secondFunction();
alert( retVal );
This is the important line:
var retVal = secondFunction();
We still have the function call. But this time it's on the right hand side of an equal sign. A single equal sign is the assignment operator, remember. So we're assigning a value to the variable on the left of the equal sign. The value we're assigning is whatever we get back from the function called secondFunction.
So bear that in mind: if you want to return a value from a function, assign it to a variable on the left of an equal sign.
After we get the value back from the function, we can do other things with it. In our simple example, we're just displaying the value in an alert box.

Function Arguments in Javascript

You can pass values over to your functions. These values are called arguments, and they go between the round brackets of the function. If you have more than one value to pass over, you separated them with commas. Let's look at an example.

Here's some new code to study that illustrates the use of arguments:
Javascript code using function arguments
In myFunction, we've set up a variable called cookiesEnabled:
var cookiesEnabled = window.navigator.cookieEnabled;
We want to test whether a user has cookies enabled in the browser. The second line of our code is this:
var retVal = secondFunction( cookiesEnabled );
In between the round brackets of our function call, we have typed the cookiesEnabled variable. This will either be true or false, depending on the user's settings. By typing a variable name between the round brackets of the function call we have set up an argument (you can also type values such as 10, "ten", or true.) The value of the cookiesEnabled variable will then handed over to the secondFunction. But look at how the secondFunction is now laid out:
function secondFunction( cookiesEnabled ) {
The second function also has a variable name between its round brackets, the same one as myFunction. But It doesn't have to be the same name. You can have different names if you like. For example:
var retVal = secondFunction( cookiesEnabled );
function secondFunction( cookiesEnabled_two ) {
The result is the same: whatever was in the variable from the calling function will be passed over to the function being called.
You could even do this:
var retVal = secondFunction( true );
function secondFunction( cookiesEnabled ) {
The function call now has a hard-coded value of true between the round brackets. A value of true will then be placed in the cookiesEnabled variable.
The code for the secondFunction just uses an IF statement to check if cookiesEnabled is true or false. It then returns a string value. We could even simplify our code like this:
Simplified function
This time, we've gotten rid of the alertString variable. Instead, we have two uses of return: one for the if part, and one for the else part. The return keyword is like a "stop" message to Javascript. After it executes a return line it bails out of the function. Any code after it won't get executed.
You can pass more than one value over to your functions. In the code below, we've set upsecondFunction to have two arguments between the round brackets:
Two arguments passed to a Javascript function
Note that the two arguments are separated by commas. When we want to call this function we can use both arguments:
The call to the function
We're passing over our two arguments with this:
var retVal = secondFunction( cookiesEnabled, isOnline );
Whatever is in these two variables will be passed to the two variables in the secondFunction.
In Javascript, however, you don't need to pass over the same number of arguments. This, for example, is perfectly valid:
var retVal = secondFunction( cookiesEnabled );
Here, we're only passing over one of the two values that secondFunction has set up. Javascript, unlike other programming languages, won't give you any error messages if the number of arguments don't agree. You could even miss out both arguments between the round brackets and Javascript won't complain. So this is OK as well (but fairly pointless):
var retVal = secondFunction();
In the code we have set up for secondFunction, the else part will be executed. In practice, though, you'd want the number of arguments to match. So if a second function is accepting two arguments then the calling line should pass over two values. It can be terribly confusing otherwise.

Variable Scope

Variables have something called scope. This is do with where variables can be seen from. Variables declared with the var keyword inside of functions cannot be seen from outside of that function. Examine this code:
function myFunction() {
var alertString = "ALERT!!!";
function secondFunction() {
alert( alertString );
The first function has a variable set up inside of its curly brackets called alertString. It is set up with the var keyword. The second function is trying to access this variable in an alert box. However, the code doesn't work, and you get an error message saying "alertString is not defined". It doesn't work because the variable alertString is local to myFunction (it's inside of this function's curly brackets and has been set up with the var keyword). So the second function can't see inside of this variable.

To remedy this, you can make variables global in scope. All this entails is declaring them outside of any functions. Like this:
var alertString = "ALERT!";
function myFunction() {
function secondFunction() {
alert( alertString );
With the variable declared outside of the two functions, at the top, the code will now work. (You can also miss out the word var keyword from inside a function to turn the variable into a global one.)
However, scope in the Javascript language can be quite complex, especially when you take into account things called closure and prototypes. So we won't cover it any further in this beginners book. Just remember to take care when declaring variables inside of functions - they can't be seen outside of that function if you declare them with the var keyword.
To end this section, let's have a look at some code that uses functions in a real setting. The HTML in the BODY section below sets up a text box and a button. (We've missed out FORM tags just to keep things simple. But you'll learn about Javascript and FORMS in a later chapter.) We want users to fill in this box. If it's empty when the button is clicked we'll display an error message just above the text box. Here's the code:
Using functions in Javascript
The BODY of the HTML has this code:
<P ID="message">First Name</P>
<INPUT TYPE ="text" SIZE="25" VALUE="" ID="Name">
<INPUT TYPE ="button" value =" SUBMIT " onClick = "validate()">
The first line is just two paragraph tags with the text "First Name" between them. The P tag also has an ID. We'll use this ID in our Javascript.
The next two lines are the tags for a text box and a button. The Text box also has an ID. When the button is clicked, it calls the validate function between the two SCRIPT tags in the HEAD section:
onClick = "validate()"
The first line of code for the validate function is this:
var textbox_value = document.getElementById("Name").value;
We're setting up a variable called textbox_value here. Into this variable we want to store the value from the text box. This is done via the getElementById property of the document object (you'll learn about getElementById in later section). Between its round brackets we have the ID from the text box. After a dot, we have value. This is enough to get the VALUE attribute from the text box.
We want to test what's in this text box so have set up an IF … ELSE statement. The IF part is this:
if (textbox_value == "") {
var error = "<span STYLE=color:red>Required</span>";
document.getElementById("message").innerHTML = error;
The variable called error just stores some HTML and CSS:
"<span STYLE=color:red>Required</span>";
This is a SPAN tag with a style applied. It will cause the test "Required" to be coloured red. Next is this line:
document.getElementById("message").innerHTML = error;
This is setting some text in the HTML. That paragraph tag we set up had an ID of message. We can use this with document.getElementById. Notice the innerHTML part after the dot. This allows you to set text in your HTML. The inner HTML is the parts between the two P tags:
<P ID="message">First Name</P>
The inner HTML is "First Name". This will be erased and replaced with the new text. The new text goes after an equal sign. For us, this is whatever is in the variable called error.
The else statement sets the innerHTML back to "First Name". We don't really need this, but it's there for testing purposes.
The return false line is also not needed in this simple piece of code. But in reality, you'd add it if you were going to send your form data somewhere. Adding return false cancels the sending so that the user can try again.

Try the code out for yourself. Typing it all out will give you some good practice of setting up HTML and Javascript. When you click your button, you should see the new text appear in red. Type some text in the text box and click the button again. The First Name text should reappear.

There's a lot more to functions, however. For example, you can create things like function expressions (also known as an anonymous function) and self invoking functions. This is intermediate to advanced stuff, however. As a beginner, it's going to be easier to stick with the simple function declarations that we've outlined in this section. For a more detailed discussion on functions, see the following pages: