Functions
Functions are the methods you set up yourself to do work for you. Whatever you need achieved through JavaScript, you can write a function for it. Functions save lots of time, as their output depends on the inputs you give them. So one function can be used to perform a number of tasks.
This page was last updated on 2012-08-21
Basic Function Structure
Now that we know about event handlers, variables, and statements, it is time to bring all our knowledge together — to create functions. Functions are the workhorses of JavaScript. A basic function looks like this:
function addNumbers(a,b) { var c = a+b; return c; }
This function will add any two numbers we give it together and then send back, or return
the sum. First, we say we're defining a function
, and give it a name. The parentheses hold the function's arguments (here, they are a
and b
). These are special variables that take on the values that you give when you call for the function, meaning you can give it any two numbers and it can add them together. This function can now be called from anywhere on the page, and whenever it is, the code between the curly braces is executed, with the arguments you passed in being substituted in.
Calling a Function
Unlike normal lines of code, functions only kick into operation when you call for them. We can call this function in the course of a normal embedded script, like so
document.write("Two plus Three is " + addNumbers(2,3));
This call makes a
2 and b
3, adds them and outputs c
, which is then written to the page. The function call is replaced by whatever the return
value is, just as a variable name is replaced with its value. We can also use this one function to add values on an event. Click the following links to add the numbers and be alerted to the answer.
Add 3 + 4 | Add 19 + 2 | Add 8 + 40
Now you can see how much flexibility this one function can give you. These links were all created the same way, which looked like this:
<a href="#" onClick="alert('Three plus Four is ' + addNumbers(3,4)); return false;">Add 3 + 4</a>
To make a link go nowhere for the purposes of executing a script, we make the href
a link to an anchor on the page and then turn off the default action by setting onClick
to return false
. The execution of the function is pretty simple — to change the outputs we just modify the call to pass new values to the arguments each time.
Once you've read through the next tutorial on objects and properties you'll even be able to do this:
A function can have as many or as few arguments as you are working with, and they can be numbers or strings. Just add in more argument variables into the function definition, separating each with a comma. If you call a function with the wrong number of arguments (less or more than it is defined as using), you will get an error.
You can also define a function with no arguments or return value,
function popup() { alert('You clicked on the page'); }
These type of functions will do the same thing every time you use them.
Return
Once you return
from a function, it stops executing. If there are more lines of code in the function definition after the return
statement, they are not executed. You can return strings and boolean variables too. For example when you're validating a form, you can test if it is filled in correctly with a function and return true or false to decide if the form is submitted.
You can use return
to stop a script before it runs. document.all
is Internet Explorer's object that holds all the page elements in it (it is Microsoft's proprietary DOM structure). So, if we write a script that uses the IE DOM, we'll want to make sure that no browsers of other types try executing the code, as they'd hit on a pile of errors. To accomplish this, we test if document.all
is supported. If it isn't, we end the script. If it is, the browser will continue on until it hits the 'real' return
value.
if (!document.all) { return; } // Internet Explorer-specific DHTML begins here
Better and more specific support detection will be addressed later.
Fixing Errors
Even from coding through the examples in the last few tutorials you've probably hit upon a number of JavaScript errors. They pop up everywhere, even for the most experienced programmers, but thankfully usually aren't too taxing to find. There are a number of ways to find the problem, and a number of common errors that I'll mention here.
Script errors will usually make themselves known down in the status bar. If you have your browser configured correctly, you can also have it popping up alerts when each error occurs. Internet Explorer gives good error messages:
From this we can find out the line and column (character) that the error occurred in, which goes a long way towards finding the root of the problem. In this case, it even tells me the problem — I used a variable x
which had not yet been given a value.
There are two types of JavaScript errors: a syntax error and a runtime error. Syntax errors are easy to pick up as they occur as soon as you load up a page and are generally spelling mistakes in your code or a case of using an undefined variable. You can hunt these down from the error messages and eliminate them. Runtime errors occur when your script is executed, by event handlers for instance. They are harder to find since they're not immediately obvious, and often require proper testing to be exposed.
Two things that cause errors all the time are:
- Using an editor that inserts a margin at the side of the code. JavaScript commands need to be right in at the left of the code if they're to work right.
- Breaking a line of code in the middle. Each JavaScript command has to all be on one line, or it will throw an error. To avoid having to scroll horizontally over long lines of code, get an editor with a word-wrap ability, which will add virtual breaks to your lines, but will not actually break up the code.
When you're trying to find the line with the error, you count down from the top of the document. Blank lines still count as lines. Below there's an error on line 6:
<html>
<head><title>Page 1</title></head>
<body>
<script type="text/javascript">
document.write("Welcome to my page"
);
</script>
</body></html>
The error in question is a command not ending on the line that it started on. Once you have found the error, check for misplaced line breaks, misspellings of JavaScript keywords, correct capitalisation of variable and function names, use of undefined variables and proper quoting (especially those apostrophes in Strings).
If you get multiple errors at a time, don't panic. Oftentimes they're all caused by one or two errors high up in your document. You should start from the top, and when you find any errors, run the script again. You'll probably find that the error total drops dramatically with each bug you catch.
Take the time to correct your errors. It's very important. If you can't get a script to work, don't include it into your page until you can. There are few things worse than encountering JavaScript errors on a page while browsing. It makes you look pretty stupid. Especially since they usually aren't that difficult to repair.