Chapter 7. Functions

Functions are an important and complex part of the JavaScript language. This chapter examines functions from several points of view. First, we discuss functions from the syntactic standpoint, explaining how they are defined and invoked. Second, we cover functions as a data type, with examples of the useful programming techniques that are made possible by treating functions as data. Finally, we consider the topic of variable scope within the body of a function and examine some of the useful function-related properties that are available to an executing function. This includes a discussion of how to write JavaScript functions that accept an arbitrary number of arguments.

This chapter focuses on defining and invoking user-defined JavaScript functions. It is also 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 the core and client-side reference sections of this book.

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

Defining and Invoking Functions

As we saw in Chapter 6, the most common way to define a function is with ...

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