Advanced Functions

main > javascript > js functions > adv js functions

These tutorials are about JavaScript and its use for ViSTA programming.

Advanced Function Features

This section can be confusing, so don't panic.

This material covers advanced features of functions. Since functions are also intimately related to objects, we also look at some other aspects of functions when we look at objects.

The Function constructor

JavaScript has a Function constructor which allows you create a variable and assign it a function as a value.

var q = new Function('a', 'b', 'return a / b;');

The Function constructor takes any number of arguments, each of which must be defined as a string, and the last of which must be the body of the code for the function.

A function defined this way can still be invoked by the variable named,
res = q(20, 5),
but technically it has no name. Instead the function name is a variable that contains a reference to that function as a value.

Such function are referred to as anonymous functions, since there is no way to refer to them by name. The benefit of declaring a function this way is that it is reparsed each time it is run, meaning, you could replace the strings that define the arguments and function body with variables, dynamically assign values to these variables, and thus rewrite the function each time it ran.

Sound confusing? Here is an example:

// declare our function
// use a variable for the body
  var c;
  var q = new Function('a', 'b', c);

// set our body variable and invoke
  c = 'a / b';
  y = q(20, 10);
// y is now equal to 2

// reset our body variable and invoke
  c = 'a * b';
  y = q(20, 10);
// y is now equal to 200
// changing the variable also
// changed the function

Since the function is reparsed each time, it can really slow down processing if it is run repeatedly.

Function Literals

Function literals are similar to the Function constructor, except they allow you to use normal syntax to assign an anonymous function a variable. Although function literal were introduced in JavaScript 1.2, they had some quirks that were not resolved until 1.5, so test your code carefully.

The syntax is as follows:

var q = function(a, b) { return a / b; }

Function literals are only parsed once and then remain static. This means they don't change until you reload the document they are in.

The function literal allows a name to be given to the function, but that name is only usable within the function. This allows for recursive functions. Even if you do name it, you can't reference outside the function except by the variable it was assigned to.

// the self reference here will work
var q = function summation(b) {
  if (b < 2) return 1;
  else return b + summation(b-1);
  }

// this call will work
z = q(20);

// this call will nott
z = summation(20);

The practical upshot of these two function features is that functions can be treated like any other type of data and assigned as values to variables. This means they can be passed to other variables. Since they are treated as an object, they are passed by reference, not by value.

The Arguments Object

All functions have a property called the arguments object. It is an array that contains a list of values of all arguments passed to the function.

If you pass five arguments to a function only expecting three, only the first three will be assigned to the argument names defined with the function, but the other two are still addressable through the arguments object.

The simplest thing you can do with it is test to make sure the right number of arguments were passed. It's length is property is equal to the number of arguments passed. If it is not equal to the number expected you have the option of actively generating an error to prevent the code from running on bad data.

function strangeEquation(x, y, q) {
  if (arguments.length != 3) {
    return 'invalid number of arguments';
    }
  var z = x * y;
  var p = q - 7;
  return (z * x % (y + 1)) / p;
  }

One benefit of this object is that it allows function to be created that accept an arbitrary number of arguments. For instance, you could have a function where the first argument is named and contains what to do with the data being passed, and all the rest of the arguments could be a random number of unnamed arguments that contain the data to be processed.

function whichWay(x) {
  for(var iter = 1; iter < arguments.length; iter++) {
    thisWay(x, arguments[iter]);
    }
  }

Function Properties

As an object, a function has other properties as well.

One is the length property, which specifies how many arguments the function is expecting.

Another is the prototype property, which we will discuss when we discuss objects.

As with objects, you can also define properties for functions. This allows you to create values that persist across repeated calls to the function. To create a new property, you can just assign it a value.

Since the function declaration is parsed before the code in the script is executed, we can put the initialization statement outside of the function.

q.counter = 0;
function q(x) {
  q.counter++;
  statements;
  }

Each time function q runs, it will increment the property q.counter by one.

Now wait, you may ask, didn't I say elsewhere that things have to be defined at some prior point in the code for JavaScript to find them and yet here is the function after the command to add a property to it.

Yes to both cases. The statement of things needing to be defined previously in the code has to do with the fact that JavaScript can have multiple code blocks in the same HTML document.

The property declaration is before the function it changes, but it is part of the same code block. What JavaScript does when it encounters a piece of script is it loads the entire script, from <script> to </script> tag, parses it, and then immediately runs any code that is not inside functions.

This means that things further down in the document will not yet be defined, including things in other sets of script tags, but everything in this set of script tags will be defined at execution time.

It is still, however, good practice to not use anything before it is defined in the code.