loading...

JavaScript – 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 9.

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 to any variables that are in scope where
they are defined. This means that JavaScript functions are
closures, and it enables important and powerful
programming techniques.

Comments are closed.

loading...