Functions

Javascript Functions

Javascript functions are the basic building blocks which can be combined together to provide more complex functions. Each of the short programs you have written so far, have started with the word function. The process of structured analysis (or top down analysis) is to take a complex problem and break it down into more manageable chunks. These chunks become the basic building blocks of your program. They let you combine to several operations (program statements) to complete some recognisable task. Once a function is written you simply call it when it is needed. You no longer have to worry about how it works. Functions are therefore one way of hiding complexity. A process known as encapsulation.

Information can be passed to a function by enclosing the information in parentheses after the name of the function. Pieces of information that are being passed to a function are called arguments, or parameters. Some functions don't take any arguments at all, other may take one or more arguments.

Functions may simply perform some task, such as opening a window, others may return a value or set of values. Javascript includes a set of build-in functions. For example, parseInt(), (to convert a string to an integer). These built-in functions can be incorporated into functions you create yourself. Two of the key built in functions are the Math Object. and the String object

Functions combine a block of statements, enclosed in braces { } under a unique name that (usually) indicates the purpose of the function. A function may be called many times within a program, thus streamlining the code.

The parameters needed by the function are enclosed inside the braces as arguments. Some functions don't require any arguments, while others may take one or more arguments. Each argument is separated by a comma.

The Javascript language has a number of built in functions which are supplemented by the functions created by the programmer. The main built in functions are

  • String
  • Math
  • Array
  • Date