Chapter 7. Functions
A function is a block of JavaScript code
that is defined once but may be executed, or invoked,
any number of times. You may already be familiar with the concept of a
function under a name such as subroutine or procedure. JavaScript functions are
parameterized: a function definition may
include a list of identifiers, known as parameters,
that work as local variables for the body of the function. Function
invocations provide values, or arguments, for the functionâs parameters.
Functions often use their argument values to compute a return value that becomes the value of
the function-invocation expression. In addition to the arguments, each
invocation has another valueâthe invocation contextâthat is the value of
the this
keyword.
If a function is assigned to the property of an object, it is known as
a method of that object. When a function is invoked
on or through an object, that
object is the invocation context or this
value for the function. Functions designed to initialize a newly created
object are called constructors. Constructors were
described in Creating Objects and will be covered again in
Chapter 8.
In JavaScript, functions are objects, and they can be manipulated by programs. JavaScript can assign functions to variables and pass them to other functions, for example. Since functions are objects, you can set properties on them, and even invoke methods on them.
JavaScript function definitions can be nested within other functions, and they have access ...
Get JavaScript Pocket Reference, 3rd 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.