Deep Tech Fusion

tech related weblog

Functions

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) {
  statements;
  return;
  }
  • 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!');
    }
  return;
  }
 
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';
testVal(x);
 
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.

Nesting

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

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

Function

Description

FF

N

IE

decodeURI()

Decodes an encoded URI

1

4

5.5

decodeURIComponent()

Decodes an encoded URI component

1

4

5.5

encodeURI()

Encodes a string as a URI

1

4

5.5

encodeURIComponent()

Encodes a string as a URI component

1

4

5.5

escape()

Encodes a string

1

3

eval()

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

1

2

3

isFinite()

Checks if a value is a finite number

1

4

4

isNaN()

Checks if a value is not a number

1

2

3

Number()

Converts an object’s value to a number

1

parseFloat()

Parses a string and returns a floating point number

1

2

3

parseInt()

Parses a string and returns an integer

1

2

3

String()

Converts an object’s value to a string

1

unescape()

Decodes a string encoded by escape()                                 

1

3

For more information click here.


Top-level Properties

Property

Description

FF

N

IE

Infinity

A numeric value that represents positive or negative infinity

1

4

4

NaN

Indicates that a value is “Not a Number”

1

4

4

undefined

Indicates that a variable has not been assigned a value

1

4

5.5


Advertisements

December 18, 2006 - Posted by | JAVASCRIPT

No comments yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: