Chapter 8. Functions

A function is a block of JavaScript code that is defined once but may be invoked, or executed, any number of times. Functions may have parameters, or arguments—local variables whose value is specified when the function is invoked. Functions often use these arguments to compute a return value that becomes the value of the function-invocation expression. When a function is invoked on an object, the function is called a method, and the object on which it is invoked is passed as an implicit argument of the function. You may already be familiar with the concept of a function under a name such as subroutine or procedure.

This chapter focuses on defining and invoking your own JavaScript functions. It is important to remember that JavaScript supports quite a few built-in functions, such as eval( ), parseInt(), and the sort() method of the Array class. Client-side JavaScript defines others, such as document.write() and alert(). Built-in functions in JavaScript can be used in exactly the same ways as user-defined functions. You can find more information about the built-in functions mentioned here in Part III and IV of this book.

Functions and objects are intertwined in JavaScript. For this reason, I’ll defer discussion of some features of functions until Chapter 9.

Defining and Invoking Functions

As shown in Chapter 6, the most common way to define a function is with the function statement. This statement consists of the function keyword followed by:

  • The ...

Get JavaScript: The Definitive Guide, 5th 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.