The Sysadmin Notebook  

Sitemap

Javascript Functions

Notes on Functions in Javascript

Contents

A function is a block of javascript code that can be called and executed by other blocks of javascript code.

Functions are called by expressions containing the name of the function, immeadiately followed by the () operator. Parameters, if required, can be specified as a comma-seperated list within the brackets. Javascript does not automatically check that parameters supplied are the of the correct type nor that the correct number of parameters have been supplied

Function Definition

Top Bottom

Functions can be defined using the 'function' keyword, followed by the function name, brackets to hold parameters and curly brackets to hold the function logic. The function can then be called by name:

function prntValue(x) {
    alert ("Variable Type: " + typeof(x) + ". Value " + x);
}
prntValue('true');

The same function can be defined using the 'function literal' notation:

var prntValue = function(x) {alert ("Variable Type: " + typeof(x) + ". Value: " + x);}
prntValue('true');

Functions defined with the function literal create unnamed functions, and are normally used on the right-side of an assignment statement. A name can be supplied in the function literal expression, but this name is only visible to the function itself (for recursive functions). Functions created with the function keyword are named functions.

Functions can also be defined using the Function() constructor, but this is neither very efficient nor very intelligible:

var prntValue = Function("x", 
'alert ("Variable Type: " + typeof(x) + ". Value: " + x);');
prntValue('true');

Functions with no 'return' statement or an empty return statement, return 'undefined'. Function parameters, named within the brackets of the function definition, become local variables within the function block and can be accessed by the name used in the definition.

Functions can contain other functions. Nested functions defined using function literal notation can appear anywhere within the the containing function definition, but functions defined using the function keyword or the Function() constructor, must appear in the top-level scope of the containing function.

Because Javascript is untyped, functions can be assigned to variables of any type, including array elements and object properties. Functions can also be used as parameters for other functions (as with the Array.sort() function).

Checking Parameters

Top Bottom

Use the typeof or instanceof operators within a function definition to check that arguments are of the required type. The number of arguments supplied can be checked by testing whether the local variables are defined or using the Arguments Object. The arguments object allows you to refer to the arguments supplied using an array-like object named arguments.

function dateFormat(d, m, y) {
//Two ways to define default values for a function
if (!y) { y = '2006');
m = m || '06';
//Check the correct number of arguments are supplied
if (arguments.length > 3) {
  throw new Error("Only " + arguments.length + " arguments supplied.");
}
if (arguments[3]) {
  var OK = confirm("Too many arguments supplied");}
  if (!OK) { throw new Error(arguments.length + supplied.") };
}

To pass named arguments to a function use an object in the parameter list. The properties of the object can then be used within the function as local variables. Note the idiom for setting default values in the function.

var birthday = {year: "1964", month: '05', day: 14};
dateFormat(birthday);
function dateFormat(aDate) {
  aDate.year = aDate.year || '2006';
  aDate.month = aDate.month || '06'
  alert(aDate.day + "-" + aDate.month + "-" + aDate.year);
}

Function Properties and Methods

Top Bottom

Functions have a length and prototype property. The length property returns the number of parameters that the function expects (according to the function definition). The length property is visible both inside and outside of the function definition. Further properties can be created for a function using '.' notation, which can be defined outside the function definition, to allow persistence across function calls

useless.countCalls = 0;
function useless(x,y,z) {
   useless.countCalls++;
   document.write("Call Number: " + useless.countCalls + "<ul>");
   document.write("<li>function called with " + useless.arguments.length + " arguments</li>");
   document.write("<li>expected to receive " + useless.length + " arguments</li>");
   checkArgs(arguments);
}
function checkArgs(args) {
    document.write("<li>Arguments required by function: " + args.callee.length + "</li></ul>");
}
document.write("Check the function definition before calling it: " + 
	useless.length + " parameters required. Prototype: " + 
	useless.prototype + "<br />");
useless("Random", 'arguments', {x: 3, y: 4}, [1,2,3], "This", "is very interesting");
useless(1,"",3,50);

The 'callee' property is supplied by the Arguments object, and refers to the function to which the Arguments object belongs.

Two methods are defined for functions: apply() and call(). Both functions allow you to invoke a function as if it were a method of an object. The first argument for both call and apply, is the object to which the function is being used as a method. The 'this' keyword can be used within the function to refer to the object. Additional arguments to 'call' are specified as a list. 'apply' requires only one additional argument, which should be supplied as an array:

var arr = new Array(1,2,3,4)
function checkArgs() {
    alert(this.name + ": called with " + arguments.length + " argument(s)");
}
var x = {name: 'apply'};
checkArgs.apply(x, arr);
x.name = 'call';
checkArgs.call(x,arr);
alert(Math.max.apply(null, arr));