A JavaScript function runs when it is prompted (invoked) by an external action or event.
// Function to compute the product of p1 and p2 function myFunction(p1, p2) { return p1 * p2; } |
A JavaScript function is declared with the “function” keyword, a name, and parentheses, which may include parameter names separated by commas. Function names follow the same rules as variables, allowing letters, digits, underscores, and dollar signs.
(parameter1, parameter2, …)
The function’s code is enclosed within curly braces: {}.
function name(parameter1, parameter2, parameter3) { // code to be executed } |
Parameters are defined in the function’s parentheses, and when called, the function receives arguments that act as local variables.