Chapter 3. Functions: The JavaScript Building Blocks

JavaScript functions provide a way to encapsulate a block of code in order to reuse the code several times. They are first-class objects in JavaScript, which means they can be treated as an object, as well as an expression or statement.

There are three basic ways to create a function:

Declarative function
A declarative function is a statement triggered by the function keyword; declarative functions are 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 Function object. It’s anonymous because it isn’t given a name, and access to the function occurs through a variable or another object property. Unlike the declarative function, an anonymous function is parsed each time it’s accessed.
Function literal or function expression
A literal function is a function expression, including parameter and body, which is used in place—such as a callback function in an argument to another function. Similar to the declarative function, function literals are also parsed only once, when the JavaScript application is loaded. The function literal can also be anonymous.

Placing Your Function and Hoisting

Problem

You’re not sure where to place your function to ensure it’s accessible when needed.

Solution

If you’re using a declarative function, you can place the function anywhere in the code. However, if you’re using a function ...

Get JavaScript Cookbook, 2nd 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.