O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

  • Following that is a name, which must start with a letter or underscore, followed by any number of letters, digits, dollar signs, 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, with the exception of the very first letter of the name, which is lowercase. Therefore, of the previous examples, getInput would be the preferred name used by most programmers. This convention is commonly referred to as bumpyCaps or camelCase.

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required