Functions

Functions are named segments of code that can be "called". For our purposes, functions are segments of code that can can be executed when the the name of the function, parentheses, and any parameters required are given in the proper form (see below for examples). Some functions are given as part of the language, such as alert() and prompt(). You may define your own functions as well which can call each other and other functions as well. See below. Also, w3schools.com has some information on this.

Examples:

The code


<!--Calling the alert() function in a script element-->
<script type="text/javascript">
alert('I run at page load, when encountered');
</script>

<!--Calling the alert() function in an event handler attribute-->
<button onclick="alert('Yup, I was clicked');">Click for alert</button>

On the page

Defining Functions

Functions are defined, normally, to encapsulate significant amounts of code so that they may be executed from different pieces of code without having to copy the code into all places that need it. In scripting it is desirable to separate large regions of code from the presentation code, the XHTML and CSS, especially in event handler attributes. Typically, function definitions go in the head inside a <script> element but they can be put at the very end so they don't slow page load (as long as they aren't need during the page load). Better still, if the JavaScript is used on multiple pages, is to use a <script> element to reference external JavaScript. Also, w3schools.com has some information on this.

To define a function:

  1. Create a script element
  2. Use the function keyword, followed by a space, and then the name of the function, followed by parentheses()
    • the name of the function should be unique
    • any parameters should be comma-separated
  3. Then use curly braces "{...}" and put the JavaScript code inside

Examples:

The code

<script type="text/javascript">
function concatenate(){
    var first=prompt('what is the first part?');
    var last=prompt('what is the last part?');
    alert(first+last);
}
<!-- this has a parameter, called echo -->
function echoTwice(echo){
    alert(echo);
    alert(echo);
}
</script>

<!--Calling the concatenate() function-->
<button onclick="concatenate();">Concatenate two strings</button>

<!--Calling the echoTwice() function with parameter (argument) 'echo'-->
<button onclick="echoTwice('echo')">Echo 'echo' twice </button>

<!--Calling the echoTwice() function with user input-->
<button onclick="echoTwice( prompt('echo what?') )">
Echo __________ Twice</button>

On the page

Keyword: return

Many of our functions do things we are interested in but are very "fire and forget", such as alert(): we don't get anything back from them. prompt() is the most obvious one that returns a value, a string to be exact. This is done inside the functions with a return statement- which ends the function and provides whatever value is after it to the calling code. Also, you can use just "return" without supplying a value to end a function without returning a value back. If you think of functions as a series of instructions that can be executed by calling the function by name then return is how return to the calling code. Understanding return is important to understanding, at least at a high level, how functions work though they are it is less useful for the small scripts we write; versus more complicated functions like you might find in a game engine - one to size a model (a bunch of triangles), one to rotate it, one to place it in the world (transform it) and another to add real 3d perspective to it. return seems less useful for JavaScript, but if you do this enough then there will be times it is the clearest and easiest way to do something.

It is also worth noting that document.getElementById() returns the node with the id that was given as a parameter. It is are related to document.body and this, but they aren't identical -- the first is accessing the body property of the document and the second is a keyword that depends on context (only inside event handler attributes). They all provide a base object reference to work from though, to access the properties of, such as style and value.

Examples:

The code

<script type="text/javascript">
function square(x){
return x*x;
}
function fourthPower(x){
//note the use of square()
return square( square( x));
}
function getSignature(){
return '<div style="text-align:right;font-weight:bold" onclick="window.location= \'http://www.cse.sc.edu/~oreillyj\';">James O\'Reilly </div>'
}
</script>

<!--Calling the square() function-->
<button onclick="alert( square( prompt('enter a number') ) );">Square a number</button>
<!--Calling the fourthPower() function-->
<button onclick="alert( fourthPower( prompt('enter a number') ) );">number^4=?</button>

<script type="text/javascript">
document.write(getSignature() );
</script>

On the page


Back to Knowledge Dump