Chapter 6. Building Reusability with JavaScript Functions
6.0. Introduction
JavaScript functions provide a way to encapsulate a block of code in
order to reuse the code several times. They’re typically created using the
function statement and syntax similar to the following:
function functionname(arg1, arg2, ..., argn) {
function body
}JavaScript functions have Function objects, which can be constructed the same as a String or Number, using the new operator:
var fn = new Function (arg1, arg2, ..., argn, functionbody);
However, using this syntax is not as efficient as using the function statement, because using a function
constructor requires that the function be parsed each time it’s called.
Functions defined with the function
statement are parsed once, when the code is loaded.
There are three basic kinds of functions:
- Declarative function
A declarative function is a statement triggered by the use of the function keyword, and parsed when the JavaScript application is first loaded.
- Anonymous function or function constructor
An anonymous function is constructed using the new operator and referencing the
Functionobject. It’s anonymous because it isn’t given a name, and access to the function occurs through a variable or another object property. It’s parsed each time it’s accessed.- Function literal or function expression
As with other JavaScript objects, functions can be both object and literal. A literal function is a function expression, including parameter and body, which is used in place—such ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access