Chapter 5: First-class functions for the novice: definitions and arguments
The chapter introduction explains why functions are central to JavaScript and introduces their status as first-class objects.
After this chapter you will be able to
- Functions in JavaScript programming. Explain why the chapter puts functions before objects: understanding JavaScript as a functional language is presented as central to writing sophisticated JavaScript code.
- Functions as first-class objects. Describe what the introduction means by calling JavaScript functions first-class objects, including examples of how they can be treated like other values.
- Declarations and expressions. Distinguish a function declaration from a function expression by where each appears, whether a name is required, and the declaration’s ability to be called before its definition.
- Arrow function syntax. Describe the arrow-function syntax and state how the section characterizes it relative to other function forms.
- Function declaration form. Describe the syntax of a function declaration and where it can appear in JavaScript code.
- Function expression uses. Distinguish function expressions from declarations by their position, optional name, and ways of invoking them.
- Immediate function invocation. Explain how a function expression can be created and called immediately.
- Immediate call syntax. Explain why parentheses or unary operators are used around immediately invoked function expressions.
- Arrow Function Syntax. Describe how an arrow function is written, including the required => operator and when parameter parentheses are optional. Explain that the syntax can be shorter than a function written with the function keyword.
- Arrow Body Return Values. Distinguish an expression-bodied arrow function from a block-bodied one and explain what each returns.
- Functions As Objectlike Values. Explain that JavaScript functions can do almost the same things as objects: be stored in variables, arrays, or object properties; be passed to and returned from functions; and have dynamically assigned properties.
- First-class function capabilities. Explain that JavaScript functions can be used like other objects: stored in variables or collections, assigned as object properties, passed to and returned from functions, and given properties of their own. Distinguish them by their additional ability to be invoked.
- Functions passed as callbacks. Describe how passing a function as an argument lets another function call it later, making the passed-in function a callback.
- Callback handoff and execution. Trace how a function passed to other code becomes a callback, using the getText and useless example. Describe how a browser event handler is also called back when its event occurs.
- Array sort comparator callback. Explain how a comparator callback lets array sort handle the sorting while the application specifies the order, including what the comparator’s return value means.
- Practical uses of functions. Describe how storing functions in a collection, attaching metadata, and memoizing results can each be useful, at the level stated in this introduction.
- Set uniqueness by reference. Describe how a Set stores unique functions and distinguish adding the same function reference twice from adding two functions with identical bodies.
- Function properties as metadata. Explain that functions are objects, so metadata can be attached directly to a function and accessed by code that consumes it.
- Encapsulation cost of attached data. Justify using a separate module-scoped variable instead of a function property when only the declaring module needs the data.
- Memoized Result Reuse. Explain how memoization stores a computed result with its arguments and returns that result when the function is called again with the same arguments, avoiding repeated computation.
- Parameters and arguments. Distinguish a parameter listed in a function definition from an argument passed when the function is invoked. Explain that a parameter can itself be passed as an argument to another function.
- Argument assignment order. Explain how arguments supplied in a function call are assigned to the function's parameters.
- Unequal argument and parameter counts. Describe what happens when a call supplies more or fewer arguments than the function has parameters, using the practice example.
- Rest parameter argument collection. Explain how a rest parameter collects arguments, trace what it receives in the multiMax example, and state where it may appear in a parameter list.
- Default parameter behavior. Explain how to define a default parameter and what happens when its matching argument is omitted or supplied.
- JavaScript argument type checks. Explain that a JavaScript function can be called with any number of arguments of any type, so code that needs an argument of a particular type must check it at runtime.
- Parameter annotations and type checking. Explain that parameter annotations specify expected argument types, which TypeScript checks at function calls, and that the annotations are removed when the code becomes JavaScript.
- Default parameter type inference. Explain how TypeScript infers a parameter’s type from its default, and when an explicit type such as string | null can be used instead.
- Inferred function return types. Explain how TypeScript infers a function’s return type from the types of values it could return, creating a union when needed. Describe how the inferred type for capitalize indicates a string parameter and a string return value.
- Explicit return type benefits. Describe where to place an explicit return-type annotation and explain why it can help catch an unhandled case in a function with complex conditionals, as illustrated by the missing zero case.
- Allowed argument type combinations. Explain why separate overload signatures are useful for a compare function that accepts two numbers or two strings, but not a mixture of the two.
- TSDoc comments alongside types. Describe what TSDoc adds to type annotations and identify the two tags the section calls most essential.
- TSDoc in declaration files. Trace how a package user can encounter TSDoc comments without reading the package’s source code.
What it builds on
- Type annotations and declarations (chapter 2) · Type annotations and declarations in TypeScript
Section by section
Introduction
The chapter introduction explains why functions are central to JavaScript and introduces their status as first-class objects.
- Functions in JavaScript programming: Explain why the chapter puts functions before objects: understanding JavaScript as a functional language is presented as central to writing sophisticated JavaScript code.
Why it matters: This explains why the book gives functions sustained attention before its advanced treatment of objects. - Functions as first-class objects: Describe what the introduction means by calling JavaScript functions first-class objects, including examples of how they can be treated like other values.
Why it matters: Treating functions as values underlies the ways the chapter will use them.
Key terms: functions, functional language, first-class objects, first-class citizens, function parameters
5.1 Defining functions
Introduces the main syntaxes for defining JavaScript functions and briefly identifies other forms and a security caution.
- Declarations and expressions: Distinguish a function declaration from a function expression by where each appears, whether a name is required, and the declaration’s ability to be called before its definition.
Why it matters: This distinction helps you recognize two common forms of function definition. - Arrow function syntax: Describe the arrow-function syntax and state how the section characterizes it relative to other function forms.
Why it matters: Recognizing the arrow syntax prepares you to identify this common function form without assuming its behavior has already been explained. - Other function definition forms: Describe the additional function forms identified here: method definitions, class fields, and generators.
Why it matters: These clues help you recognize function definitions that do not look like ordinary declarations. - Function constructor caution: Explain how the Function constructor creates a function and why the section advises caution.
Why it matters: It flags a rarely used way to define functions whose runtime interpretation of code strings warrants caution.
Key terms: function declaration, function expression, function keyword, arrow function, =>, this keyword, method definition, object literal, class field, generator
5.1.1 Function declarations and function expressions
This section distinguishes function declarations from function expressions and explains how function expressions can be invoked immediately.
- Function declaration form: Describe the syntax of a function declaration and where it can appear in JavaScript code.
Why it matters: Recognizing a declaration helps you distinguish it from a function used as part of another statement. - Function expression uses: Distinguish function expressions from declarations by their position, optional name, and ways of invoking them.
Why it matters: Function expressions let you define a function where it is needed without requiring a declared name. - Immediate function invocation: Explain how a function expression can be created and called immediately.
Why it matters: It shows that calling a function does not require first giving it a separate identifier. - Immediate call syntax: Explain why parentheses or unary operators are used around immediately invoked function expressions.
Why it matters: The syntax prevents the parser from treating an intended immediate call as a declaration or an error.
Key terms: function declaration, function keyword, parameter names, function body, function expression, argument, return value, immediately invoked function expression, IIFE, immediate function
5.1.2 Arrow functions
This section explains arrow-function syntax and return behavior, with a brief sidebar on using console.assert to check examples.
- Arrow Function Syntax: Describe how an arrow function is written, including the required => operator and when parameter parentheses are optional. Explain that the syntax can be shorter than a function written with the function keyword.
Why it matters: Recognizing the parameter and arrow syntax lets you read and write this common short form of a function. - Arrow Body Return Values: Distinguish an expression-bodied arrow function from a block-bodied one and explain what each returns.
Why it matters: The body form determines whether an arrow function returns its result automatically or needs an explicit return. - Console Assertion Checks: Explain how console.assert checks an expectation and when it emits a message.
Why it matters: It helps you interpret the checks used in the section's code examples.
Key terms: arrow function, arrow function operator, fat-arrow operator, parameters, expression, block of code, return statement, undefined, console.assert, truthy
5.2 The versatility of JavaScript functions
The section shows that JavaScript functions can be used in almost the same ways as objects.
- Functions As Objectlike Values: Explain that JavaScript functions can do almost the same things as objects: be stored in variables, arrays, or object properties; be passed to and returned from functions; and have dynamically assigned properties.
Why it matters: This explains why functions can be stored, passed around, and given properties in JavaScript.
Key terms: functions, objects, properties, arguments
5.2.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 can be used like other objects: stored in variables or collections, assigned as object properties, passed to and returned from functions, and given properties of their own. Distinguish them by their additional ability to be invoked.
Why it matters: Treating functions as values makes the patterns later in the chapter possible. - Functions passed as 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 connection between first-class functions and callbacks prepares you to recognize callback code. - Functional programming connection: Explain that first-class functions help enable functional programming, which solves problems by composing functions rather than specifying sequences of steps, and state the benefits the section mentions.
Why it matters: It shows a broader reason that treating functions as values is useful.
Key terms: first-class objects, functions, invokable, callback function, argument, functional programming, composing functions, imperative programming
5.2.2 Callback functions
This section explains how functions serve as callbacks, then uses event handling and array sorting to show when other code calls them.
- Callback handoff and execution: Trace how a function passed to other code becomes a callback, using the getText and useless example. Describe how a browser event handler is also called back when its event occurs.
Why it matters: It helps you recognize who actually calls a function you have supplied. - Inline callback definitions: Explain why a callback used in one place can be defined where it is passed rather than given a separate name elsewhere.
Why it matters: A one-use callback can stay close to the code that needs it. - Array sort comparator callback: Explain how a comparator callback lets array sort handle the sorting while the application specifies the order, including what the comparator’s return value means.
Why it matters: You can choose an ordering without implementing a sorting algorithm. - Default sort ordering caveat: Describe why calling sort without a comparator can give surprising results for numbers and why the section recommends localeCompare for user-facing string order.
Why it matters: The default sort order may silently differ from the order you intended.
Key terms: callback, callback parameter, event handler, function, expression, module namespace, sort, comparator, default comparator, localeCompare
5.3 Fun with functions
Introduces three ways JavaScript functions can be used and the benefit of each.
- Practical uses of functions: Describe how storing functions in a collection, attaching metadata, and memoizing results can each be useful, at the level stated in this introduction.
Why it matters: These examples show why functions are useful beyond a single immediate call.
Key terms: collection, callbacks, metadata, minified code, memoization
5.3.1 Storing functions in a collection
This section shows how to keep a collection of callback functions unique by using a Set, and explains what counts as the same function.
- Unique callback collections: Explain why a collection of callbacks should avoid duplicates and why checking an array for them is a poor approach.
Why it matters: The risk of duplicate calls explains why the collection needs to enforce uniqueness. - Set uniqueness by reference: Describe how a Set stores unique functions and distinguish adding the same function reference twice from adding two functions with identical bodies.
Why it matters: Reference equality determines which additions a Set treats as duplicates.
Key terms: callbacks, duplicates, array, Set, reference equality, functions are objects
5.3.2 Attaching metadata to functions
This section explains when attaching data to a JavaScript function is useful, when it weakens encapsulation, and why React uses a function’s displayName for debugging.
- Function properties as metadata: Explain that functions are objects, so metadata can be attached directly to a function and accessed by code that consumes it.
Why it matters: This explains why metadata can travel with the function it describes. - Encapsulation cost of attached data: Justify using a separate module-scoped variable instead of a function property when only the declaring module needs the data.
Why it matters: The ability to attach data does not mean it is the best place to keep private state. - React display names under minification: Describe React’s displayName example and explain why it can remain useful when a function’s declared name is lost during minification.
Why it matters: It gives a concrete reason to attach descriptive metadata despite the encapsulation trade-off.
Key terms: functions, objects, metadata, encapsulation, module’s scope, displayName, name property, React DevTools, minified
5.3.3 Memoizing functions
This section explains how memoization reuses results of expensive function calls and why a reusable wrapper can hold the cache.
- Memoized Result Reuse: Explain how memoization stores a computed result with its arguments and returns that result when the function is called again with the same arguments, avoiding repeated computation.
Why it matters: It explains why repeated calls with the same inputs can become faster. - Reusable Memoization Wrapper: Describe why the example uses a wrapper function to cache answers rather than putting caching logic directly in isPrime.
Why it matters: The wrapper separates caching from the calculation while keeping the cache private. - Example Wrapper Cache Limits: Distinguish the single-argument limitation of the example wrapper from memoize-one's choice to retain only the most recent result.
Why it matters: Cache design affects both which functions a wrapper supports and how much memory it uses.
Key terms: memoization, function arguments, previously computed values, wrapper function, encapsulation, isPrime, single argument, memoize-one, memory overhead
5.4 Arguments and function parameters
This section distinguishes function parameters from arguments and explains how JavaScript assigns arguments to parameters, including when their counts differ.
- Parameters and arguments: Distinguish a parameter listed in a function definition from an argument passed when the function is invoked. Explain that a parameter can itself be passed as an argument to another function.
Why it matters: The distinction makes it easier to describe what a function defines versus what each call supplies. - Argument assignment order: Explain how arguments supplied in a function call are assigned to the function's parameters.
Why it matters: Positional assignment lets you predict which value each parameter receives. - Unequal argument and parameter counts: Describe what happens when a call supplies more or fewer arguments than the function has parameters, using the practice example.
Why it matters: It helps you predict parameter values even when a call does not match the function's parameter list.
Key terms: parameter, argument, function definition, invocation, arguments, parameters, assigned, order, excess arguments, undefined
5.4.1 Rest parameters
This section explains how a rest parameter collects remaining function arguments into an array and shows its use in a multiplication example.
- Rest parameter argument collection: Explain how a rest parameter collects arguments, trace what it receives in the multiMax example, and state where it may appear in a parameter list.
Why it matters: Rest parameters let a function handle a variable number of remaining arguments as an array.
Key terms: rest parameter, ellipsis (...), remainingNumbers, SyntaxError: parameter after rest parameter
5.4.2 Default parameters
This section explains how JavaScript default parameters supply omitted arguments, what values they can use, and when they make functions easier to use.
- Default parameter behavior: Explain how to define a default parameter and what happens when its matching argument is omitted or supplied.
Why it matters: A caller can omit a routine option without losing the ability to choose a different value. - Default value evaluation: Describe the kinds of values a default parameter can use and how defaults are evaluated across parameters.
Why it matters: Defaults need not be fixed strings or numbers, though more elaborate expressions deserve care. - Sensible defaults and readability: Justify using simple defaults while being cautious about defaults that reference earlier parameters.
Why it matters: Defaults are most useful when they remove repetitive choices without making a function harder to read.
Key terms: default parameters, matching argument, default value, primitive values, objects, arrays, functions, previous parameters, sensible defaults, code readability
5.5 Declaring functions in TypeScript
This introduction explains why JavaScript function arguments can require runtime checks and how missing types can allow errors to spread.
- JavaScript argument type checks: Explain that a JavaScript function can be called with any number of arguments of any type, so code that needs an argument of a particular type must check it at runtime.
Why it matters: This explains why a JavaScript function call may need a check before it uses an argument. - Risks of missing explicit types: Describe how missing explicit typing and implicit conversion can contribute to errors, including an unexpected null value that spreads through an application despite testing.
Why it matters: It shows why tests alone may not catch every problem caused by an unexpected value.
Key terms: arguments, type check, runtime, explicit typing, implicitly convert, null
5.5.1 Defining parameter types
This section explains how TypeScript checks function parameter types, including rest and default parameters, without adding runtime checks.
- Parameter annotations and type checking: Explain that parameter annotations specify expected argument types, which TypeScript checks at function calls, and that the annotations are removed when the code becomes JavaScript.
Why it matters: It distinguishes TypeScript’s argument checks from checks performed by the running JavaScript. - Typed rest parameters: Describe what the number[] annotation says about a rest parameter in this section’s example.
Why it matters: It shows how the section’s argument typing applies to a rest parameter. - Default parameter type inference: Explain how TypeScript infers a parameter’s type from its default, and when an explicit type such as string | null can be used instead.
Why it matters: It shows when a default saves an annotation and when an explicit annotation expresses a broader allowed type.
Key terms: parameter, type annotation, TypeScript compiler, runtime type check, rest parameters, number[], remainingNumbers, default parameters, infer, action
5.5.2 Defining return types in TypeScript
This section explains how TypeScript infers function return types and why developers may annotate them explicitly.
- Inferred function return types: Explain how TypeScript infers a function’s return type from the types of values it could return, creating a union when needed. Describe how the inferred type for capitalize indicates a string parameter and a string return value.
Why it matters: It explains why a function can be type-checked without an explicit return annotation. - Explicit return type benefits: Describe where to place an explicit return-type annotation and explain why it can help catch an unhandled case in a function with complex conditionals, as illustrated by the missing zero case.
Why it matters: It shows when an optional annotation can make a type-checking error more useful.
Key terms: return type, infer, union, type annotations, explicit return type, type annotation, type checker
5.5.3 Function overloading
This section explains how TypeScript function overloads describe permitted combinations of argument types without creating separate runtime implementations.
- Allowed argument type combinations: Explain why separate overload signatures are useful for a compare function that accepts two numbers or two strings, but not a mixture of the two.
Why it matters: Overloads express relationships between argument types that independent parameter unions do not. - Type checking versus runtime behavior: Distinguish TypeScript overload signatures from separate implementations at runtime, and describe the limited role of the as keyword in the example.
Why it matters: This keeps compile-time checks distinct from what the JavaScript function does at runtime. - Arrow function overload syntax: Describe how the section says to provide overload signatures for an arrow function despite the earlier syntax being limited to function declarations.
Why it matters: The same permitted call patterns can be expressed for arrow functions.
Key terms: function overloading, overload signatures, type checker, as keyword, function overloads, function keyword, arrow functions, type annotation
5.5.4 Documenting functions with TSDoc
This section explains how TypeScript type annotations and TSDoc comments help readers and editors understand functions, including functions supplied by packages.
- Human value of type annotations: Explain how function type annotations help people understand a function, not just help the type checker catch errors.
Why it matters: Type annotations can serve as useful information for someone using or reading a function. - TSDoc comments alongside types: Describe what TSDoc adds to type annotations and identify the two tags the section calls most essential.
Why it matters: TSDoc makes a function’s explanation available through TypeScript-aware tools as well as in its source code. - TSDoc in declaration files: Trace how a package user can encounter TSDoc comments without reading the package’s source code.
Why it matters: Good API comments can reach package users through their editors, even when they are not reading the implementation.
Key terms: type annotations, TypeScript-aware editor, TSDoc, @param, @returns, .d.ts files, TSDoc comments, TypeScript types
5.6 Summary
Where this is used later
- Invoking functions (chapter 6) · Introduces functions before considering how they are invoked.
- Iterating within a function with generators (chapter 8) · Develops generators beyond their identifying * character.
- Classic OOP with class and extends (chapter 9) · Provides the class context for class-field syntax.
- Invocation as a method (chapter 6) · Introduces function declarations and function expressions.
- Invocation as a constructor (chapter 6) · Function declarations and function expressions
- Using arrow functions to get around function contexts (chapter 6) · How arrow functions are defined.
- Referencing surrounding variables from callbacks (chapter 7) · Understanding callbacks supports the later discussion of referencing surrounding variables from them.
- (chapter intro) (chapter 7) · Introduces callback functions, used here as an example of where closures matter.
Concepts explained in this chapter
- functionA callable unit of code that can receive arguments and return a value.
- function declarationA function definition is source code that declares a function and specifies its parameters and executable body.
- function expressionA function expression is a JavaScript expression that creates a function and occurs as part of another expression or statement.
- function argumentA value supplied to a function call for binding to a corresponding parameter.
- expressionAn expression is a JavaScript construct that evaluates to a value and can occur within a larger expression or statement.
- first-class functionA function that can be treated as a value, including being assigned, passed as an argument, or returned.
- callA function invocation is an operation that calls a function and supplies zero or more arguments to it.
- first-class objectA value that can be assigned, stored, passed as an argument, and returned from a function.
- default parameterA default parameter is a function parameter that receives a specified fallback value when the corresponding argument is omitted or undefined.
- callbackA function supplied to another computation to be invoked when a specified event occurs or operation completes.
- immediately invoked function expressionAn immediately invoked function expression is a function expression that is invoked immediately after it is created.
- arrow functionThe => token used to define an arrow function in JavaScript.
- Array.prototype.sortA JavaScript method that sorts an array in place using a default ordering or a supplied comparison function.
- comparison functionA compare function is a sorting callback that returns a negative, positive, or zero number to order two items.
- TypeScriptA statically typed superset of JavaScript that compiles to JavaScript.
- type hintsSyntax attached to a TypeScript declaration or expression that explicitly specifies expected types and can supply information for type checking and inference.
- type inferenceThe compile-time determination of types from surrounding declarations, expressions, or values without requiring explicit annotations.
- TypeScript compilerA tool that compiles TypeScript source code to JavaScript, optionally targeting a selected ECMAScript version.
- setA collection of unique items with no duplicate membership.
- assertionAn assertion is a regular-expression condition that checks surrounding text without consuming it as part of the match.
- generatorA generator is a JavaScript function whose execution can suspend and resume while producing a sequence of values through an iterator.
- default valueA default value is a predefined value substituted when an expected input is not provided.
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.
