Function definitions in JavaScript
Syntax
The syntax for a function definition is given below, where there can be any number of parameters and any number of statements. Notice that the parameters are separated by commas and the statements are separated by semicolons. The function definition itself does not end with a semicolon, as it is not executed.
function myFunction(parameter1, parameter2) {
statement1;
statement2;
statement3;
}
A value can be returned using the statement return
. Notice the conventions being used:
- lines are indented evenly (here four spaces, but two spaces is also common)
- the name of the function is given in camelCase
In choosing the name of an identifier, make sure that the first symbol is a letter or an underscore. (Typically using an underscore as the first symbol is reserved for special functions rather than ordinary user-defined functions.) The remaining symbols can be letters, underscores, digits, or $
.
To define a local variable inside a function, be sure to use var
; omitting var
often results in the creation of a global variable instead.
Parameters
A function may have zero or more parameters.
Unlike in some other languages, the number of arguments used in a JavaScript function call does not need to equal the number of parameters in the function definition. If the function call uses more arguments than there are parameters, the first argument is used as the first parameter, the second as the second, and so on, with the unmatched arguments being ignored. If instead the function call uses fewer arguments than there are parameters, again the first argument is used as the first parameter, the second as the second, and so on, with any unmatched parameter receiving the default value undefined
.