Basic Functions

main > javascript > js functions > basic js functions

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

Functions

function: a named segment of code that can be invoked to perform some task, or function

A function is a statement block that has been assigned a name.

That name allows it to be called or referred to, meaning the it can be invoked by name to perform some task, or function. This means that you can create a piece of code that will not run until specifically called for or invoked by another piece of code.

Being able to defer the execution of code until it is called for is a very powerful tool. It allows us to step out of batch processing mode and instead function in an event driven environment.

Defining Functions

In JavaScript a function is defined as follows:

function functionName(arguments) {
  statements;
  return;
  }
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).