Higher-Order Functions

Learn about functional programming paradigm to use composable pure functions.

Prerequisites:

  • Understand arguments vs parameters

  • Anonymous functions

  • Functions Definitions can be other function’s arguments

Summary/Overview

Higher Order Functions are the key part of Functional Programming. Functional programming is a different style of programming, just like Object Oriented Programming (OOP) is a programming style. Functions in functional programming are small compo sable functions usually only a couple of lines long. Functional Programming also relies on ‘pure functions’. Pure functions are functions that given the same input will always produce the same result, no side effects. For Example:

// Pure Function 
const foo = function(number){
    return number * 2
}
let numbers = foo(num);

// Function with side effects
let num = 2;

const bar = function(){
    num = 2 * num
}

In the above code example functional foo will always take a number and return that number doubled. The function bar however is very specific and is modifying a value outside of function bars scope. This is what would be considered a side-effect. Functions with side-effects are harder to reuse and debug. In contrast our pure function foo, becomes more reusable and composable.

What does composable mean?

For example let’s say I wanted to double a number and then find the square root.


//Pure Function
function sqr(num){
 return Math.sqrt(num)
}
//Pure Function
const doubled = function(number){
    return number * 2
}
const double = doubled(10)
const number = sqr( double )


These functions are composable because in javascript there is an Execution Stack. The execution stack is a fancy way the javascript engine handles functions when they are executed. When a function is invoked, it is put onto the top of the stack. If a function invokes a function like in the case below:

let number =
Execution Stack
          Function foo 2nd on stack 1st one off
          Function sqr 1st on stack last one off

Sqr function would be invoked first and placed on the stack, then foo would be invoked and placed on the stack. In this case our function foo() is an argument of the sqr function. To be clear in this case sqr is on the stack but no code is run inside of sqr because the function foo is an argument must be executed first and return its output, in this case a number. The execution stack is just simple queue or stack that operates on first in last out, also known as FILO.

To summarize, if a functions invokes another function, the parent function cannot finish its execution until the child function is removed from the stack or completes.

Setup

Step 1 - Create a repo named functional-array on github.

  • Create a repo on github - Creating a repo lesson only do till part 6 - Git Clone

  • Clone the repo to your local machine.

  • Make sure when you run git clone you are in the desired directory

All the following problems will be based on the below animals array.

const Animals = [   
     {name: "Fluffykins" , species: "rabbit" },
     {name: "Caro" , species: "dog" },
     {name: "Hamilton" , species: "dog"},
     {name: "Harold", species: "fish"},
     {name: "Ursula" , species: "cat"},
     {name: "Jimmy", species: "fish"}
]

Copy this array into a new file called arrayFilter.js in your challenges/week2/functional-array

Note this is your file path: challenges/<current week#>/functional-array

Problem 1 - Array Filtering

Part 1 - For Loop Filter

Create a Function that takes an array for a parameter and returns an array of just the dogs from the animals array.

Constraints

  1. Must use a for loop

  2. For loop must be in the function

  3. Function must return an array.

  4. Store the output of the function in a variable called dogs

  5. Console.log the variable dogs

Remember to commit your work with git when you hit a milestone in your work.

  1. git add . Note* - will add your work to staging

  2. git status Note* - confirm you have the desired files added in green

  3. git commit -m “ message about commit ”

Part 2 - Array Filter Method

In the same file, arrayFilter.js create a new function that uses the array filter method. You should have the same result as in part 1. Tips: Google search javascript array filter or see Mozilla Array Filter

Constraints

  1. Must use filter method inside a new function

  2. Must return an array of dogs

  3. Must console.log the result and have the same output as step 1

Problem 1 - Review

Note * If in class wait. We will review as a group.

Video Review Functional Programming #1 Filter

Problem 2 - Array Map

Part 1 - Map with For Loop

First create a new file arrayMap.js and copy the above animals array into the file.

Now create a function that takes an array for a parameter and returns an array of strings, the names from the animals array.

Constraints

  1. Must use a for loop.

  2. For loop must be in a function.

  3. Function must return an array of strings.

  4. Store the output of the function in a variable called animalNames

  5. Console.log the variable animalNames

Part 2 - Array Map Method

In the same file, arrayMap.js create a new function that takes in array as a parameter and returns an array of names, however instead of looping you must use array map method.

Tips: Google search javascript array map or see Mozilla Array Map

Constraints

  1. Must use map method inside function

  2. Function must return an array of names

  3. Console.log the result and have the same output as step 1

Problem 2 - Review

Note * If in class wait. We will review as a group.

Video:Functional Programming #2 Map

Problem 3 - Array Reduce

Part 1 - For Loop Reduce

Create a new file called reduceArray.js in your Challenges/week2/functional-array Now copy the Orders array below into your reduceArray.js file.

const Orders = [
     {amount: 250},
     {amount: 400},
     {amount: 100},
     {amount: 325}
]

Create a function that takes in an array as a parameter and returns the total amount of all the orders

Constraints

  1. Must have a function with a for loop inside

  2. Must function must return a number that is the total amount

  3. Save the output of the function in a variable called total.

Part 2 - Reduce Method

Inside of reduceArray.js create a new function that takes an array as a parameter and returns the total amount, however this time use the array reduce method instead. Tips: Mozilla Array Reduce or google javascript array reduce method.

Constraints

  1. Must use reduce method

  2. Function must return number that is the total of order amounts

  3. Must save the result in a variable

  4. The console.log variable must match the step from part 1

Problem 3 - Review

Note * If in class wait. We will review as a group.

Video: Functional Programming #3

Recap

Push up your code to git hub, this way we have updated work in our online github remote repository.

In this lesson we introduced you to functional programming. We want to create small reusable code not 50+ long line functions.

Key Points

  • Pure Functions - we want to write functions that take in a value, do work on it then output ( return ) the value. This way we reduce side-effects

  • Filter, Map and Reduce are pre-existing array methods that exist on the array prototype. There are many more existing methods for arrays and objects and string. Searching for existing solutions on the prototype can be very valuable and powerful.

  • Mozilla Javascript Documentation is probably the best resource when looking up existing methods on arrays, objects, strings.

Example:

Last updated