Deep Tech Fusion

tech related weblog


A function is a reusable code-block that will be executed by an event, or when the function is called.

Defining Functions

In JavaScript a function is defined as follows:

function functionName(arguments) {
  • The definition starts with the keyword function.
  • This is followed by the name of the function.
  • After that comes a set of parentheses containing the arguments the function is expecting to receive. Each argument must be a variable name. These variables are created by declaring them as arguments and are local to the function.
  • After this comes the curly braces that delimit the statement block that makes up the body of the function.
  • The last statement in the statement block should be a return statement, which returns control back to whatever called the function. The keyword return can stand alone or it can be followed (with no intervening line break) by a value to be returned. If no value is specified, then the function returns undefined.
function testVal(x) {
  if (isNaN(x)) {
    window.alert ('x is not a number!');
function strangeEquation(x, y, q) {
  var z = x * y;
  var p = q - 7;
  return (z * x % (y + 1)) / p;

Invoking Functions

You invoke, or call, a function by name. The name needs to be followed by a set of parentheses that contain zero or more values to be passed to the function. The number of values being passed should be equal to the number of arguments the function has. The values are assigned to the arguments in the order in which they appear in the list.

Invoking a function:

x = 'bob';
x = 1;
y = 2;
q = 3;
strangeEquation(x, y, q);

If you want to pass values of a certain type, you need to test for this yourself since JavaScript, being an untyped language, does not check.

If you pass too many values, then the additional values do not get assigned to named arguments. They can still be accessed within the function, just not as named variables.

If you pass too few values then the remaining arguments will be undefined. JavaScript will not error out on this, but your code most probably will not run correctly.


In JavaScript, function definitions can be nested. This is a reasonably unique feature. It exists because JavaScript uses functions to define objects (which are discussed elsewhere) and sometimes objects have functions defined internally, thus requiring a function within a function.

There are strict limits on where nested functions can be defined. A function can only be defined at the top level of the wherever it is defined. What this means is that it can be defined at the global level, or inside functions, but they cannot be defined within any other type of statement block. So, for instance, you cannot define a function inside an if statement.

Some browsers consider a function defined within another function to be local to that function. Therefore nesting functions is not a good idea unless you have a reason for local sub-functions defined within functions (such as the object instance noted above).

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) {

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.

The top-level properties and functions can be used on all of the built-in JavaScript objects.

Top-level Functions

FF: Firefox, N: Netscape, IE: Internet Explorer







Decodes an encoded URI





Decodes an encoded URI component





Encodes a string as a URI





Encodes a string as a URI component





Encodes a string




Evaluates a string and executes it as if it was script code





Checks if a value is a finite number





Checks if a value is not a number





Converts an object’s value to a number



Parses a string and returns a floating point number





Parses a string and returns an integer





Converts an object’s value to a string



Decodes a string encoded by escape()                                 



For more information click here.

Top-level Properties







A numeric value that represents positive or negative infinity





Indicates that a value is “Not a Number”





Indicates that a variable has not been assigned a value





December 18, 2006 Posted by | JAVASCRIPT | Leave a comment

Custom JavaScript functions

10) addEvent()

Surely a staple to event attachment! Regardless to what version you use written by whatever developer, it does what it says it does. And of course as you might of known, I’ve put together quite a handy version myself recently of addEvent() with some help from the contest winner and Mark Wubben along with a few minor syntax adjustments. But just to be fair to Scott Andrew, here is the original that started it all.
Scott Andrew’s original addEvent() function

function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
else if (elm.attachEvent) {
var r = elm.attachEvent(‘on’ + evType, fn);
return r;
else {
elm[‘on’ + evType] = fn;

9) addLoadEvent()

Originally written by Simon Willison and highly adopted by many others as a simple way to add events to trigger after the page has loaded. This of course attaches all your events to the onload event handler which some still see as necessary, nevertheless it does exactly what it’s supposed to, and does it well.
addLoadEvent() by Simon Willison

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != ‘function’) {
window.onload = func;
else {
window.onload = function() {

Of course another method is to simply assign multiple event listeners to the window by using addEvent() as described in number 10 as follows:
assigning multiple load events to window


8) getElementsByClass()
Originially written by nobody in particular. Several developers have implemented their own version and no one single version has proven to be better than another. As you might expect, my humble self has even had a crack at it. This function was spawned from developers needing a quick and elegant way of grabbing elements by a className and to a developer’s surprise, it’s not an original DOM method as one might think…afterall, we have getElementById, getElementsByName(), getElementsByTagName, what the hell happened to getElementsByClass??? Here it is in all its glory:

getElementsByClass by Dustin Diaz

function getElementsByClass(searchClass,node,tag) {

	var classElements = new Array();

	if ( node == null )

		node = document;

	if ( tag == null )

		tag = '*';

	var els = node.getElementsByTagName(tag);

	var elsLen = els.length;

	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');

	for (i = 0, j = 0; i < elsLen; i++) {

		if ( pattern.test(els[i].className) ) {

			classElements[j] = els[i];




	return classElements;


Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

7) cssQuery()

version 2.0.2

getElementsByTagName? Pah!


cssQuery() is a powerful cross-browser JavaScript function that enables querying of a DOM document using CSS selectors. All CSS1 and CSS2 selectors are allowed plus quite a few CSS3 selectors.



elements = cssQuery(selector [, from]);

where selector (required) is a valid CSS selector and from (optional) is a document, element or array of elements which is filtered by selector.

The function returns a JavaScript array of elements. If there is no match, an empty array is returned.

Some examples:

// find all paragraphs that are direct descendants //  of the document body var tags = cssQuery("body > p");  // find all elements with the "href" attribute var tags = cssQuery("[href]");  // find all anchor elements with "href" equal to "#" var tags = cssQuery("a[href='#']"); // find all images contained by the above anchors var images = cssQuery("img", tags);  // find all lists var tags = cssQuery("dl,ol,ul");  // query an external xml document var tags = cssQuery("my|:root>my|link", myXMLDoc);  // just plain complicated var complex = "p>a:first-child+input[type=text]~span"; var tags = cssQuery(complex);

6) toggle()

<a href=’; target=’_parent’><img src=’;n=af051ed1&#8242; border=’0′ alt=”></a>

To be totally honest, there are probably more variations of this function than there needs to be. The history of ‘toggling’ basically comes down to showing/hiding an element upon an event being fired. To make matters much simpler, I too have put one together. But by no means is it considered the ultimate toggle function, but it does do the basic functionality of showing and hiding.

toggle() by the masses

function toggle(obj) { 
	var el = document.getElementById(obj); 
	if ( != 'none' ) { = 'none'; 
	else { = ''; 

5) insertAfter()

As far as I know, Jeremy Keith sort of came up with this idea even though one would have thought this too would be a DOM core method. But just like getElementsByClass, it isn’t. So rather than pulling the function straight out of the book, I’ll leave that up to you to buy it yourself. Instead I’ve pulled this simple method from public domain:

insertAfter() on public domain

function insertAfter(parent, node, referenceNode) { 
	parent.insertBefore(node, referenceNode.nextSibling); 

4) inArray()

This too is very sad that this isn’t part of the DOM core functionality. But hey, it makes for fun references like this! This function however isn’t quite a function; it’s a prototype that extends the DOM Array object. I remember one day thinking to myself “surely I can do this in PHP, it’s gotta be in JavaScript.” Well, this extension makes it work just like you’d expect if you’re a PHP developer. Here is a version from EmbiMEDIA

inArray Prototype Array object by EmbiMedia

Array.prototype.inArray = function (value) { 
	var i; 
	for (i=0; i < this.length; i++) { 
		if (this[i] === value) { 
			return true; 
	return false; 

3, 2, & 1) getCookie(), setCookie(), deleteCookie()
<a href=’; target=’_parent’><img src=’;n=af051ed1&#8242; border=’0′ alt=”></a>

I honestly don’t know what I would do without these guys. I hate the DOM implementations of setting cookies in JavaScript. In PHP it’s so easy, and it’s easy for one main reason, they work just like the functions below. All three of these functions were found to be public domain and free to use.

getCookie(), setCookie(), deleteCookie() open domain

function getCookie( name ) {
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
return null;
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ';', len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );

function setCookie( name, value, expires, path, domain, secure ) {
var today = new Date();
today.setTime( today.getTime() );
if ( expires ) {
expires = expires * 1000 * 60 * 60 * 24;
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name+'='+escape( value ) +
( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
( ( path ) ? ';path=' + path : '' ) +
( ( domain ) ? ';domain=' + domain : '' ) +
( ( secure ) ? ';secure' : '' );

function deleteCookie( name, path, domain ) {
if ( getCookie( name ) ) document.cookie = name + '=' +
( ( path ) ? ';path=' + path : '') +
( ( domain ) ? ';domain=' + domain : '' ) +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';

Prototype function $

function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
return elements;

December 18, 2006 Posted by | JAVASCRIPT | 1 Comment