Chapter 6. Functions
Functions are the building blocks that you use to assemble a program out of discrete, reusable code routines. But in JavaScript, thatâs only part of the story.
JavaScript functions are also genuine objectsâinstances of the Function
type. They can be assigned to variables and passed around your code. They can be declared in an expression, without a function name, and optionally using a streamlined arrow syntax. You can even wrap one function in another to create a private package that includes the functionâs state (called a closure).
Functions are also at the core of JavaScriptâs object-oriented support. Thatâs because custom classes are really just a special type of constructor function (as youâll see in Chapter 8). Sooner or later, everything in JavaScript comes back to functions.
Passing a Function as an Argument to Another Function
Problem
Youâre calling a function that expects you to provide your own function. Whatâs the best way to pass it?
Solution
Many functions in JavaScript accept, or even require, a function thatâs passed as an argument. Some operations ask for a callback function that will be triggered when a task is complete. Others need to use your function to complete a broader task. For example, many methods of the Array
object ask you to provide a function for sorting, converting, combining, or selecting data. The array then uses your function multiple times, until it has processed every element.
There are several different ...
Get JavaScript Cookbook, 3rd 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.