O'Reilly logo

JavaScript Cookbook, 2nd Edition by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required