Chapter 15. JavaScript Functions, Objects, and Arrays
Just like PHP, JavaScript offers access to functions and objects. In fact, JavaScript is actually based on objects, because—as you’ve seen—it has to access the DOM, which makes every element of an HTML document available to manipulate 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 write
, which you have already seen being used in document.write
, you can easily create your own functions. Whenever you have a more 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 symbols, or underscores.
-
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).
Function names are case-sensitive, so all of the following strings refer to different functions: getInput
, GETINPUT ...
Get Learning PHP, MySQL & JavaScript, 4th 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.