User Defined Functions


User Defined Functions.  We have already done a fair amount with built-in functions in JavaScript.  Now we are going to start working on developing our own functions.  These will start off very simple and increase in complexity.

In many respects, the reasons for developing your own functions are essentially the same as for using built-in functions.  Probably ,the main reason for developing functions boils down to

  • code re-usability

Using functions can also help code debugging and development because particular functionalities are more segmented and it is usually easier to develop and debug smaller segments.

Basic Function Syntax.  There are some rules that must be followed with respect to naming functions and their overall layout.

  • Naming Rules

    • the first letter must be a letter, the rest of the characters can include letters, numbers, dashes and underscores.

    • function names are case sensitive so that WildWillies is different from wildwillies.

    • you need to have a pair of parentheses following the name

    • you can have variable names within the parentheses, but we won't develop this option until the next web page

    • you always want to make sure your variables and functions have different names

  • Delineation

    • in order to determine where the function begins and ends you need to use a pair of curly brackets or braces, { }.

Our First Example.  Our first function is entirely simple and makes use of some built in functions and properties in JavaScript.  You should call the following file DisplaySize.html and upload and execute it.


<title>Determining Display Size</title>
<script language="JavaScript">

function getScreenSize()
var screen_height = window.screen.availHeight;
var screen_width = window.screen.availWidth;

window.document.write("<P>The screen height is " + screen_height + " pixels.</P>");
window.document.write("<P>The screen width is " + screen_width + " pixels</P>"); 


<body bgcolor = "990000" link ="cccccc" vlink="cccccc">
<P align=center>
<a href="#" onClick="getScreenSize(); return false;">
<font size=5><b>Click here to get your screen size</b></font></a>


Notice how I have placed the function in the header section of the page.  It is invoked when the link is clicked.

When you upload and access the page you should see the following with the link.



After clicking on the link you are likely to see something like the following.  Obviously, my taskbar at the bottom is taking away a little bit of my display area.




The next page will start to involve slightly more sophisticated functions where we pass in arguments and pass the results of the function back to the calling routine.