JavaScript Functions

In addition to having access to dozens of built-in functions (or methods) such as write, which you have already seen being used in document.write, you can easily create your own functions. Whenever you have a more complex piece of code that is likely to be reused, you have a candidate for a function.

Defining a Function

The general syntax for a function is:

function function_name([parameter [, ...]])
{
    statements
}

The first line of the syntax indicates that:

  • A definition starts with the word function.

  • A name follows that must start with a letter or underscore, followed by any number of letters, digits, dollar symbols, or underscores.

  • The parentheses are required.

  • One or more parameters, separated by commas, are optional (indicated by the square brackets, which are not part of the function syntax).

Function names are case-sensitive, so all of the following strings refer to different functions: getInput, GETINPUT, and getinput.

In JavaScript there is a general naming convention for functions: the first letter of each word in a name is capitalized except for the very first letter, which is lowercase. Therefore, of the previous examples, getInput would be the preferred name used by most programmers. The convention is commonly referred to as bumpyCaps.

The opening curly brace starts the statements that will execute when you call the function; a matching curly brace must close it. These statements may include one or more return statements, which force the function to cease ...

Get Learning PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.