Chapter 15. JavaScript Functions, Objects, and Arrays

Just like PHP, JavaScript offers access to functions and objects. In JavaScript objects are the primary means for accessing the Document Object Model (DOM), because—as you’ve seen—every element of an HTML document is available to be manipulated as an object.

The usage and syntax are also quite similar to those of PHP, so you should feel right at home as I take you through using functions and objects in JavaScript, as well as through an in-depth exploration of array handling.

JavaScript Functions

In addition to having access to dozens of built-in functions (or methods), such as log, which you have already seen being used in console.log, you can easily create your own functions. Whenever you have a relatively 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 shown here:

function function_name([parameter [, ...]]) {
  statements
}

The first line of the syntax indicates the following:

  • A definition starts with the word function.

  • A name follows that must start with a letter or underscore, followed by any number of letters, digits, dollar signs, or underscores, the same rules as for any other identifier.

  • 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).

Like all identifiers in JavaScript, function names are case-sensitive, ...

Get Learning PHP, MySQL & JavaScript, 7th 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.