1 of 24

Higher Order Functions

CSCI 344: Advanced Web Technologies

Spring 2025

2 of 24

Announcements

  1. All grades are up-to-date. Please check your grade and any comments I’ve given you.
  2. Added study guides and practice quizzes
  3. Quiz 2a next Friday:
    • Make sure you feel comfortable writing loops, functions, and event handlers from scratch.
    • Doing the practice problems is the best way to study

3 of 24

Outline

  1. Introduction to higher-order functions
  2. Array Methods: forEach, map, filter, and reduce
  3. Exercises

4 of 24

Outline

  1. Introduction to higher-order functions
  2. Array Methods: forEach, map, filter, and reduce
  3. Exercises

5 of 24

Intro to Higher-Order Functions

  • “Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.”
  • “Higher-order functions allow us to abstract over actions, not just values.

6 of 24

Simple Example: “Do something in X seconds”

// callback function 1

function sendAnEmail() {

console.log("Pretend the function sends an email...");

}

// callback function 2

function drawSomethingToTheScreen() {

console.log("Pretend the function draws on the screen...");

}

// Higher order function: “Call callback function in X milliseconds”

setTimeout(sendAnEmail, 500);

setTimeout(drawSomethingToTheScreen, 1000);

See: 00-example-callback-functions.js

7 of 24

Demo (lecture files)

8 of 24

What just happened?

  • A callback function is passed as an argument to another function (called a “higher order” function).
  • The higher order function will invoke the callback function when appropriate.

Examples:

  • setTimeout(callback, milliseconds): “I will invoke the callback function after X milliseconds has elapsed.”
  • setInterval(callback, milliseconds): “I will invoke the callback function every X milliseconds.”

9 of 24

Why would you want to do this?!

10 of 24

Example: Iteration

There are many computation actions that are so common in JavaScript that they’ve been abstracted into “higher order functions.” One example is iteration:

  • What you tend to do every time? visit each item sequentially
  • What tends to change? (depending on the context): The operation performed on each item

Given that this is a common design pattern, why not separate things out:

  1. One function for iteration
  2. One function to define the action that happens as you iterate

11 of 24

Example: The forEach Higher Order Function

In this example, the printItemToConsole function is invoked for every element in the list:

// listconst fruit = ['apple', 'orange', 'banana', 'mango', 'peach'];

// function to be invoked for each list item�const printItemToConsole = item => console.log(item);

// putting it all together: print each item in the list to the console:�fruit.forEach(printItemToConsole);

12 of 24

Example: Iteration with anonymous function

You can also just specify the function definition as an argument directly:

const fruit = ['apple', 'orange', 'banana', 'mango', 'peach'];��fruit.forEach(item => console.log(item));�

…or do it all in one line!

['apple', 'orange', 'banana', 'mango', 'peach'].forEach(

item => console.log(item);

);

13 of 24

What else could you do?!

You can also just specify the function definition as an argument directly:

const fruit = ['apple', 'orange', 'banana', 'mango', 'peach'];�

fruit.forEach(item => console.log(item));

// other stuff you might want to do:

fruit.forEach(drawToScreen);�fruit.forEach(appendToObject);�fruit.forEach(getNutrientValue);�fruit.forEach(addToDropdownMenu);

14 of 24

Common Error: Definition v. Invocation

const fruit = ['apple', 'orange', 'banana', 'mango', 'peach'];

// function 1 (printing to the console):�const printItemToConsole = item => console.log(item);

// what’s wrong with this?

fruit.forEach(printItemToConsole());

15 of 24

Outline

  1. Introduction to higher-order functions
  2. Array Methods: forEach, map, filter, and reduce
  3. Exercises

16 of 24

What is forEach actually doing?

  • The functions passed into forEach, map, and filter accept three parameters:
    • The item (required)
    • The index of the item in the array (optional)
    • The original array (optional)
  • Most of the time, you only use the first parameter.
  • Under the hood, the higher-order array method is invoking the item-level function on every element of the array and passing in all three parameters.

17 of 24

Example: forEach “Under the Hood”

class SuperArray extends Array {

forEach(callbackFn) {

for (let i = 0; i < this.length; i++) {

// invokes the callback function with all three parameters:

callbackFn(this[i], i, this);

}

}

}

const myArray = new SuperArray(1, 2, 3, 4, 5);

�const myCallback(item, i, arr) => console.log(`${i}: ${item} ${arr}`)

myArray.forEach(myCallback);

18 of 24

map

The map() method creates a new array from calling a function for every array element.

  • Identical to forEach EXCEPT it returns an array where each array element is the return value from the map function.

Example:

const numbers = [65, 44, 12, 4];

const squareEm = num => num ** 2;

const newArr = numbers.map(squareEm);

19 of 24

Map Demo

20 of 24

filter

The filter() method creates a new array filled with elements that pass a test provided by a function.

  • The function passed to the filter function must return true or false (indicating whether the item should be included or excluded in the resulting array.

�Example:

const my_nums = [1, 2, 3, 4, 5];

const nums_greater_than_2 = my_nums.filter(item => item > 2);

console.log(nums_greater_than_2);�

21 of 24

filter Demo

22 of 24

reduce

The reduce() method executes a reducer function for array element. It returns a single value: the function's accumulated result.

  • Its purpose is to perform summative / aggregation tasks on an array:
    • What’s the biggest number?
    • What’s the sum of all the numbers:

�Example:

const sum_of_nums = my_nums.reduce((a, b) => a + b);

console.log(sum_of_nums);

23 of 24

Parameters for reduce and the reducer function

callbackFn – Executed for each element in the array. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. Arguments:

  • accumulator – The value resulting from the previous call to callbackFn. On the first call, its value is initialValue if the latter is specified; otherwise its value is array[0].
  • currentValue – The value of the current element.
  • currentIndex – The index position of currentValue in the array.
  • array – The array reduce() was called upon.

initialValue Optional

A value to which accumulator is initialized the first time the callback is called. If initialValue is specified, callbackFn starts executing with the first value in the array as currentValue.

24 of 24

reduce Demo