Chapter 5. Functions

JavaScript functions are a key part of the language, but they’re not quite what they seem. They look like they would belong in the family of statements, but in actuality, they’re objects just like all the others we’ve covered in the last chapter. You can define a function, create a new one, even print one out.

Thanks to this functionality, you can assign a function to a variable, an array element, or even pass one as an argument to another function call. This makes using functions a very handy and flexible beastie, but also a confusing one.

It’s easy to get lost in discussions of anonymous functions as compared to function statements, function expressions, and references to literal functions. Add in concerns about function closure and memory leaks, as well as properties inherited by all functions, and you can see they are not a trivial JavaScript construct.

Defining a Function: Let Me Count the Ways

There are three primary approaches to creating functions in JavaScript: declarative/static, dynamic/anonymous, and literal. It’s important to understand the impact of each type of declaration before using it.

Tip

Many programming tasks can be accomplished with the simple declarative/static approach. You may not want to use anonymous or literal functions while getting started, but it’s useful to know what they are if you have to read someone else’s code. (And eventually, of course, you’ll probably want to use them!)

Declarative Functions

The most common type of function ...

Get Learning JavaScript 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.