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:
functionfunction_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 ...
Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition 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.