Function definitions in JavaScript

Syntax

The syntaxThe rules for expression. for a function definition is given below, where there can be any number of parametersThe formal name of an input to a function. 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 conventionsA consistent style used to make code more readable to humans. 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 identifierThe name that you choose for a variable or another creation., 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 variableNames defined within a function. inside a function, be sure to use var; omitting var often results in the creation of a global variableNames with meaning everywhere in the program. instead.

Parameters

A function may have zero or more parametersThe formal name of an input to a function..

Unlike in some other languages, the number of argumentsA value specified as an input to a function. used in a JavaScript function call does not need to equal the number of parametersThe formal name of an input to a function. 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.