Chapter 3: Chapter 3. First-class functions for the novice: definitions and arguments
The introduction explains why functions are central to JavaScript and establishes that they are first-class objects.
After this chapter you will be able to
- Functions as a JavaScript foundation. Explain why the chapter starts with functions rather than objects: the book treats understanding JavaScript as a functional language as crucial to writing more sophisticated code.
- First-class function status. Describe what it means here for JavaScript functions to be first-class objects, including the examples of referencing them with variables, declaring them with literals, and passing them as function parameters.
- Functions as execution units. Explain why functions are central to JavaScript code on a page: apart from global code executed during page building, the code described here runs within functions, usually as a result of function invocation.
- Object-like function capabilities. Describe the object capabilities listed in this section and explain that JavaScript functions can do almost the same things, including being stored, passed, returned, and given properties.
- First-class function capabilities. Explain that JavaScript functions are objects that can be stored, passed, and returned like other objects, while also being callable.
- Passed functions and callbacks. Describe how passing a function as an argument lets another function call it later, making the passed-in function a callback.
- Callback meaning and timing. Explain that a callback is a function supplied for other code to call at an appropriate point, and that the call need not be asynchronous.
- Passed callback execution flow. Trace how useless receives getText as an argument, refers to it through its callback parameter, and invokes it with callback().
- Array sort comparator callback. Describe how an array’s sort method uses a supplied comparison function and what its positive, negative, and zero results mean.
- Properties on functions. Explain that JavaScript functions resemble other objects in that properties can be attached to them.
- Function property storage mechanism. Trace how the store object's add() method uses an id property on a function to admit it only once and cache it.
- Memoization and repeated inputs. Explain how memoization associates computed results with function arguments so a later call with the same arguments can reuse a result instead of recalculating it.
- Function property answer cache. Trace how the isPrime example creates and uses an answers cache attached to the function itself.
- Function literals as values. Explain that a function literal creates a function value, much as a numeric literal creates a number, and that functions can be used as values like strings and numbers.
- Four function definition forms. Distinguish the four groups introduced here: declarations and expressions are common but different; ES6 arrow functions use less syntax; constructors build functions from strings; and generators can be exited and reentered while retaining variable values. State that the definition form can affect when and how a function can be invoked, without explaining those later mechanics.
- Declaration and expression placement. Distinguish a function declaration, which stands as a separate statement, from a function expression, which forms part of another expression, such as an assignment or function argument. Describe the required parts of a declaration and note that it can be nested inside another function.
- Function names and invocation. Explain why a function declaration needs a name but a function expression may omit one, and describe how an unnamed function expression can still be invoked.
- Immediate function invocation. Explain how a function expression can be created and called immediately rather than first being called through an identifier.
- Arrow parameter and operator syntax. Describe how parameters and the fat-arrow operator form an arrow function definition, including when parameter parentheses are required.
- Expression and block return values. Distinguish an arrow function with an expression after => from one with a block of code, and describe how each produces its return value.
- Parameters and arguments. Distinguish a parameter listed in a function definition from an argument passed when the function is invoked. Explain that a parameter's value can itself be passed as an argument to another function.
- Argument assignment and mismatches. Trace how supplied arguments are assigned to parameters in order. Describe what happens without an error when a call has extra arguments or leaves parameters without arguments.
- Rest parameter argument collection. Explain how prefixing a function’s last parameter with `...` collects the remaining passed-in arguments into an array, and state why the rest parameter must be last.
- Default Parameter Behavior. Explain how to define a default parameter and what happens when a call omits or supplies the matching argument.
What it builds on
- Executing JavaScript code (chapter 2) · Introduces JavaScript execution during page building.
- Registering event handlers (chapter 2) · The earlier discussion of registering event handlers supplies a browser-event example.
Section by section
Introduction
The introduction explains why functions are central to JavaScript and establishes that they are first-class objects.
- Functions as a JavaScript foundation: Explain why the chapter starts with functions rather than objects: the book treats understanding JavaScript as a functional language as crucial to writing more sophisticated code.
Why it matters: It explains why the book gives functions sustained attention before advanced object concepts. - First-class function status: Describe what it means here for JavaScript functions to be first-class objects, including the examples of referencing them with variables, declaring them with literals, and passing them as function parameters.
Why it matters: Treating functions as values is the foundation for the uses of functions developed later in the chapter.
Key terms: functions, functional language, first-class objects, first-class citizens, function parameters, literals
3.1 What’s with the functional difference?
This section explains why functions matter in JavaScript and introduces their object-like capabilities.
- Functions as execution units: Explain why functions are central to JavaScript code on a page: apart from global code executed during page building, the code described here runs within functions, usually as a result of function invocation.
Why it matters: It explains why understanding functions is so important for writing JavaScript. - Object-like function capabilities: Describe the object capabilities listed in this section and explain that JavaScript functions can do almost the same things, including being stored, passed, returned, and given properties.
Why it matters: These capabilities are the basis for using functions flexibly throughout the book.
Key terms: functions, modular units of execution, function invocation, global JavaScript code, objects, first-class objects, arguments, properties
3.1 Do you know?
This section poses review questions about callbacks, arrow functions, and default parameter values without explaining their answers.
3.1.1 Functions as first-class objects
This section explains what makes JavaScript functions first-class objects, how that enables callbacks, and how it relates to functional programming.
- First-class function capabilities: Explain that JavaScript functions are objects that can be stored, passed, and returned like other objects, while also being callable.
Why it matters: Treating functions as values makes the examples and techniques that follow possible. - Passed functions and callbacks: Describe how passing a function as an argument lets another function call it later, making the passed-in function a callback.
Why it matters: This connects first-class functions to the callback concept used throughout JavaScript. - Functional programming connection: Distinguish composing functions to solve problems from specifying a sequence of steps, and explain why first-class functions support the former.
Why it matters: It shows one broader programming style that becomes possible when functions can be treated as values.
Key terms: first-class objects, functions, invokable, callback function, arguments, functional programming, composing functions, imperative programming
3.1.2 Callback functions
This section explains how functions serve as callbacks, from direct invocation and browser events to comparison functions used by array sorting.
- Callback meaning and timing: Explain that a callback is a function supplied for other code to call at an appropriate point, and that the call need not be asynchronous.
Why it matters: This lets you recognize callbacks even when they are called immediately rather than by an event. - Passed callback execution flow: Trace how useless receives getText as an argument, refers to it through its callback parameter, and invokes it with callback().
Why it matters: Tracing this small example makes it clear who supplies a callback and who actually runs it. - Inline callback definition benefits: Explain why defining a function where an expression can appear can be useful when that function is not referenced elsewhere.
Why it matters: A callback used in just one place need not require a separate global name. - Array sort comparator callback: Describe how an array’s sort method uses a supplied comparison function and what its positive, negative, and zero results mean.
Why it matters: A comparator lets you choose the ordering without implementing the sorting algorithm.
Key terms: callback, event handler, asynchronously, getText, useless, callback parameter, callback(), expression, global namespace, first-class objects
3.2 Fun with functions as objects
The section introduces functions as objects that can have properties and gives two high-level uses: managing related functions and remembering computed values.
- Properties on functions: Explain that JavaScript functions resemble other objects in that properties can be attached to them.
Why it matters: This makes it possible to think of a function as more than code to invoke. - Collections of related functions: Describe how storing functions in a collection can help manage related functions, such as callbacks to invoke when something of interest occurs.
Why it matters: Keeping related callbacks together makes them easier to manage. - Remembering computed values: Explain that memoization lets a function remember previously computed values to improve the performance of later invocations.
Why it matters: The remembered values explain why later calls may perform better.
Key terms: functions, properties, objects, collection, callbacks, memoization, previously computed values, subsequent invocations
3.2.1 Storing functions
This section shows how to store unique callback functions by marking each function with an id property and caching it under that id.
- Unique callback collection rationale: Explain why a callback collection should avoid duplicates and why scanning an array for each addition is a poor approach.
Why it matters: It explains the problem the function-property technique is meant to solve. - Function property storage mechanism: Trace how the store object's add() method uses an id property on a function to admit it only once and cache it.
Why it matters: The function itself carries the marker that lets this collection reject a second addition.
Key terms: callbacks, unique functions, duplicates, store, add(), id property, nextId, cache
3.2.2 Self-memoizing functions
This section explains how a function can cache its computed results on itself, reuse them for repeated inputs, and trade memory for speed.
- Memoization and repeated inputs: Explain how memoization associates computed results with function arguments so a later call with the same arguments can reuse a result instead of recalculating it.
Why it matters: It explains why repeated calls can become faster without changing what the caller asks the function to do. - Function property answer cache: Trace how the isPrime example creates and uses an answers cache attached to the function itself.
Why it matters: The function property lets the cache persist between calls while the function is alive. - Caching benefits and costs: Describe the benefits and drawbacks the section identifies for a self-memoizing function.
Why it matters: A faster repeated call comes with costs that matter when deciding whether to cache results.
Key terms: memoization, previously computed values, function arguments, isPrime, answers, cache, property key, performance, memory, business logic
3.3 Defining functions
Introduces functions as values and distinguishes four ways to define them at a high level.
- Function literals as values: Explain that a function literal creates a function value, much as a numeric literal creates a number, and that functions can be used as values like strings and numbers.
Why it matters: Thinking of functions as values makes the different ways of defining them easier to understand. - Four function definition forms: Distinguish the four groups introduced here: declarations and expressions are common but different; ES6 arrow functions use less syntax; constructors build functions from strings; and generators can be exited and reentered while retaining variable values. State that the definition form can affect when and how a function can be invoked, without explaining those later mechanics.
Why it matters: The form used to define a function can affect when it is available and how it behaves.
Key terms: function literal, function value, first-class objects, function declarations, function expressions, arrow functions, function constructors, generator functions
3.3.1 Function declarations and function expressions
This section distinguishes function declarations from function expressions and explains how a function expression can be invoked immediately.
- Declaration and expression placement: Distinguish a function declaration, which stands as a separate statement, from a function expression, which forms part of another expression, such as an assignment or function argument. Describe the required parts of a declaration and note that it can be nested inside another function.
Why it matters: Where a function appears in the code helps you tell which form you are looking at. - Function names and invocation: Explain why a function declaration needs a name but a function expression may omit one, and describe how an unnamed function expression can still be invoked.
Why it matters: An unnamed function expression can still be called when another reference provides a way to reach it. - Immediate function invocation: Explain how a function expression can be created and called immediately rather than first being called through an identifier.
Why it matters: This explains a common JavaScript pattern in which a function runs as soon as it is defined. - Immediate call parser distinction: Explain why an immediate call to an unnamed function expression needs syntax that marks it as an expression, and describe the parentheses or unary-operator alternatives shown.
Why it matters: The surrounding syntax explains why some immediate-call forms work while a similar-looking standalone form throws an error.
Key terms: function declaration, function expression, function body, function name, parameter name, immediately invoked function expression, IIFE, immediate function, function call parentheses, JavaScript parser
3.3.2 Arrow functions
This section introduces arrow functions as a concise form of function expression and explains their parameter syntax and two ways of producing a return value.
- Arrow functions and function expressions: Explain how an arrow function can express the same callback as a function expression with less syntax, using the sorting example from the section.
Why it matters: The sorting comparison shows why the shorter syntax is useful without changing the callback's task. - Arrow parameter and operator syntax: Describe how parameters and the fat-arrow operator form an arrow function definition, including when parameter parentheses are required.
Why it matters: These rules let you recognize and write the basic shape of an arrow function. - Expression and block return values: Distinguish an arrow function with an expression after => from one with a block of code, and describe how each produces its return value.
Why it matters: The distinction prevents confusion about whether an arrow function returns a value automatically.
Key terms: arrow functions, function expressions, callback, parameter names, fat-arrow operator, =>, expression, block of code, return statement, undefined
3.4 Arguments and function parameters
This section distinguishes function parameters from arguments and explains how JavaScript assigns arguments when a call supplies more or fewer values than the function defines parameters for.
- Parameters and arguments: Distinguish a parameter listed in a function definition from an argument passed when the function is invoked. Explain that a parameter's value can itself be passed as an argument to another function.
Why it matters: The distinction lets you describe precisely what a function declares and what a caller supplies. - Argument assignment and mismatches: Trace how supplied arguments are assigned to parameters in order. Describe what happens without an error when a call has extra arguments or leaves parameters without arguments.
Why it matters: This explains the parameter values a function sees even when a call supplies too many or too few arguments.
Key terms: parameter, argument, function definition, invocation, arguments, parameters, excess arguments, undefined
3.4.1 Rest parameters
Explains how ES6 rest parameters collect extra function arguments into an array and illustrates their use in a calculation.
- Rest parameter argument collection: Explain how prefixing a function’s last parameter with `...` collects the remaining passed-in arguments into an array, and state why the rest parameter must be last.
Why it matters: This lets a function accept extra arguments without handling each one as a separately named parameter. - MultiMax argument flow: Trace how `multiMax(3, 1, 2, 3)` assigns its arguments and uses the rest-parameter array to multiply the first value by the largest remaining value.
Why it matters: The example makes the division between an ordinary parameter and a rest parameter concrete.
Key terms: rest parameters, ellipsis (...), SyntaxError: parameter after rest parameter, multiMax, first, remainingNumbers, descending order
3.4.2 Default parameters
This section explains why ES6 default parameters are useful, how omitted arguments receive defaults, and how default values are evaluated.
- Default Parameter Behavior: Explain how to define a default parameter and what happens when a call omits or supplies the matching argument.
Why it matters: Defaults let callers omit a common value without taking away their ability to choose another one. - Motivation and Earlier Workaround: Explain why default parameters help when most calls use the same value, and describe the earlier JavaScript workaround shown here.
Why it matters: It shows the repetition and manual checking that default parameters replace. - Default Value Evaluation: Describe what kinds of values defaults can use, when and in what order they are evaluated, and why the section urges restraint with complex defaults.
Why it matters: It explains both the flexibility of defaults and why simple uses are often clearer.
Key terms: default parameters, matching argument, default value, function overloading, typeof operator, undefined, evaluated on each function call, previous parameters
3.5 Summary
3.6 Exercises
Where this is used later
- Invoking functions (chapter 4) · Develops the idea of code running through function invocation.
- Using closures with callbacks (chapter 5) · Recognizing callbacks supports the later discussion of using closures with them.
- Invocation with the apply and call methods (chapter 4) · Introduces callback functions.
- Working with promises (chapter 6) · Assumes familiarity with callback functions.
- External code and markup (chapter 14) · Functions can have other functions as properties.
- Sets (chapter 9) · Introduces sets as another way to work with collections of unique items.
- Working with generator functions (chapter 6) · Explores generator functions beyond this introduction.
- Registering identifiers within lexical environments (chapter 5) · The distinction between function declarations and function expressions.
Concepts explained in this chapter
- function declarationA JavaScript statement that defines a named function.
- function expressionA function defined as an expression rather than a declaration, producing a function value that can be assigned or passed around.
- callbackA function supplied to other code to be invoked later when a condition or event occurs.
- first-class objectA value that can be assigned, passed as an argument, returned, and otherwise handled like an ordinary value.
- arrow functionA concise JavaScript function syntax that captures this lexically from its creation context rather than creating its own binding.
- default parameterA function parameter with a default value used when the caller omits an argument or passes undefined.
- immediately invoked function expressionA function expression that is defined and invoked immediately in the same syntactic construct.
- rest operatorA function parameter syntax that collects remaining supplied arguments into a single array-like value.
- function parameterA variable listed in a function definition that receives a corresponding argument when the function is invoked.
- memoizationA technique that stores computed results so repeated calls with the same inputs can reuse them.
- lambdaA function that has no name.
- attributeA named association on an object that holds a value or provides accessor behavior.
- syntactic sugarLanguage syntax that makes an operation easier to read or write without adding new underlying capabilities.
- generatorA JavaScript function that can yield values, suspend execution, and later resume with its local state preserved.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
