20.7. User-Defined Functions

JavaScript supports user-defined functions. User-defined functions allow you to better organize your code into discrete, reusable chunks.

User-defined functions have the following syntax:

function <function_name> ( <list_of_arguments>) {
  ...code of function...
  return <value_to_return>;
}

For example, the following function will space-fill the string passed to it to 25 characters and return the filled string:

function spacefill (text) {
  while ( text.length < 25 ) {
    text = text + " ";
  }
  return text;
}

Elsewhere in your code, you can use this function similarly to the following:

address = spacefill(address);

This would cause the variable address to be space-filled to 25 characters and reassigned to itself.

Strictly speaking, the return statement is optional. However, it is usually a good idea to at least include a status code return (success/fail) for all your functions.

The arguments passed to a function can be of any type. If multiple arguments are passed to the function, separate them with commas in both the calling statement and function definition, as shown in the following examples:

Calling syntax:

spacefill(address, 25)

Function syntax:

function spacefill (text, spaces) {

Note that the number of arguments in the calling statement and in the function definition should match. If you supply fewer variables than the number expected by the function, the remaining variables will remain undefined. If you specify more variables than the number expected ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP 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.