JavaScript Functions and Arrays

We'll continue our JavaScript discussion today with a discussion on functions and arrays. We assume that you already know that functions are very important when trying to write re-usable code, or code that is only executed when some event happens. For today, we'll focus on how to define functions in JavaScript, how to invoke them, and some of the scope rules - where are variables visible in a program. We'll also discuss about how to use arrays in JavaScript.

Function Definitions

In JavaScript, functions can be declared using the function keyword, followed by the function name, and, in parantheses, the list of parameters (without a var declaration). The actual function definition is enclosed in curly brackets. The return keyword is used to return a value or just terminate the function.


function function-name(parameter-list){
    declarations and statements
}

JavaScript also supports annonymous functions: functions without a name, that can be defined as an expression and stored in a variable. The variable can then be used as a function name when invoking the function:


var function-name = function(parameter-list){
    declarations and statements
}

For example, the function below returns the sum of its two parameters.


/* Returns the sum of x and y */
function doAdd(x, y) {
  var sum = x + y;
  return sum;
}

Function Invocation

Invoking a function in JavaScript, whether built-in or user-defined, is the same as in PHP, Java, and other languages: use the name of the function, followed by the list of arguments (if applicable) in parantheses. For example, myNumber = parseInt(myString) invokes the built-in parseInt function with the argument myString and stores the value returned by the function in the variable myNumber. The arguments are passed by value, so the original values in the caller are not changed.

Variables Scope

In JavaScript, global variables, visible everywhere on the page (in the script), including inside functions, are the variables declared outside functions, either explicitly (using the keyword var) or implicitly (just used without declaration), or variables declared implcitly (no var) inside functions.

Local variables, visible only inside functions, are the function's parameters and variables explicitly declared using var anywhere inside the function.


Arrays

JavaScript arrays can be created using "new Array()", which creates an empty array, or "new Array(size)", to create an empty array of given size, or just "[]" for an empty array, or "[1,2,3]" for an array initialized with 3 integers. The indexes in an array start with 0.

Arrays in JavaScript may be homogeneous or heterogeneous — that is, composed of just one data type, or a mix of data types. In fact, arrays can even have other arrays as their elements.

<script>
  var friends = ["Bill", "Doug", "Jim", "Sarah", "Jill"];
</script>

Whitespace is not important; each new array item can be declared on a new line, if helpful for readability:

<script>
  var primes = [2,
                3,
                5,
                7,
                11];
</script>

Arrays in Javascript increase their size automatically, as needed. To get the size of an array, use the .length property of the arrays


window.alert(primes.length);

Scope - Revisited

As we discussed earlier, arguments are passed from caller to the functions by value, so argument values in the caller are not changed by the actions of the function. However, arrays and objects arguments are "references" so the contents might be changed by the functions, and those changes will be visible outside functions.

Practice Problems

  1. Write a function that takes one argument and returns the factorial of that number.
  2. What is the output of the following script?
    
    function fun1 (x) {
       x = x + 3;
       y = y + 4;
       document.writeln("<br> FUN1: "+x+ "," +y);
    }
    
    function fun2 () {
       var y;
       x = x + 10;
       y = y + 20;
       document.writeln("<br> FUN2: "+x+ "," +y);
    }
    
    x = 1; 
    y = 2;
    
    document.writeln("<br> MAIN #1: "+x+ "," +y);
    fun1(x);
    document.writeln("<br> MAIN #2: "+x+ "," +y);
    fun1(y);
    document.writeln("<br> MAIN #3: "+x+ "," +y);
    fun2();
    document.writeln("<br> MAIN #4: "+x+ "," +y);        
            
  3. Write a function indentPrint(N, str1, str2) that outputs the following:
    N dashes, followed by the string str1, then <br>
    N dashes, followed by the string str2, then <br>
    Use document.write() for output. You can assume N is an integer.
    • Write a function “sumArray” as follows:
      Input: an array
      Output: the sum of the elements of that array
    • Write test code to create an array and call “sumArray” on it.
  4. What is the output of the following script?
    
            function printme( unknown ) {
                document.writeln("
    we got ", unknown); } var array1 = [“cat”, “mouse”, “dog”]; var array2 = [“bird”, “plane”]; var x = 1; printme (array1); printme (array2[1]); printme (x); array1[x] = 57; printme (array1);
  5. 
            function changeMe1( z ) {
                z[0] = 75;
             }
             function changeMe2( a, b) {
                a = b;
             }
             var array1 = [17, 21, 42];
             var array2 = [14, 19];
             var array3 = [7, 8, 9];
             var x = 63;
    
             changeMe1 (array1);
             document.writeln("
    array1: ", array1); changeMe1 (x); document.writeln("
    x: ", x); array1 = array2; document.writeln("
    array1: ", array1); changeMe2 (array1, array3); document.writeln("
    array1: ", array1);