GithubHelp home page GithubHelp logo

u1_lesson_hof's Introduction

Higher Order Functions

High Order Functions

Lesson Overview

In this lesson, we'll learn all about High Order Functions and their usage in javascript.

Getting Started

  • fork and clone
  • Open this repo in your code editor with code .
  • Create an index.js file via the command line

Objectives

  • Review "for loops"
  • Learn about the "forEach" method
  • Learn common array methods .map(), .filter(), and .reduce()
  • Learn how to chain these methods

Lesson Instructions

In JavaScript, functions are first-class citizens, which means, we can pass functions around like values. Higher Order Functions are functions that pass a function as an argument or return a function as a value, adding another layer of complexity.

Higher Order Functions w/ Food!

map, filter, reduce with emoji

Take a look at the graphic above and see if you can guess what each of these methods does to the original values... We'll reference back to this throughout the lesson and it will make more sense!

Review: for loops!

const numbers = [1, 2, 3, 4, 5]

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i])
}

// Will console.log 1 2 3 4 5
  • You can call the .forEach() method on any array and pass it a function to execute on each item in the array.
const numbers = [1, 2, 3, 4, 5]

numbers.forEach((element) => {
    console.log(element);
  })

// Will console.log 1 2 3 4 5
  • .map() will loop over a given array and produce a new array with new values based on logic you define in the function passed into .map().

  • In the cases below, we are storing the results from the methods in a variable so that we can console.log it and see the results.

const words = ['the', 'world', 'is', 'round', 'like', 'an', 'orange']

const wordLengths = words.map((word) => {
    return word.length
  })

// console.log(wordLengths) will return [ 3, 5, 2, 5, 4, 2, 6 ]
const words = ['the', 'world', 'is', 'round', 'like', 'an', 'orange']

const wordsWrappedInX = words.map((word) => { 
    const newWord = 'x' + word + 'x'
    return newWord
  })

// console.log(wordsWrappedInX) will return [ 'xthex', 'xworldx', 'xisx', 'xroundx', 'xlikex', 'xanx', 'xorangex' ]
  • .filter() will loop through a provided array and produce a new array that only contains some of the items. Each item in the array runs through a function. If the function returns true, the item is included in the new array.
const words = ['the', 'world', 'is', 'round', 'like', 'an', 'orange']

const shortWords = words.filter((word) => { 
    return word.length <= 3 
  })

// console.log(shortWords) will return [ 'the', 'is', 'an' ]
const words = ['the', 'world', 'is', 'round', 'like', 'an', 'orange']

const wordsThatStartWithR = words.filter((word) => {
    return word[0] === 'r'
  })

// console.log(wordsThatStartWithR) will return ['round']
  • The .reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value that is returned.
  • It can help to think of the accumulator as "the running total so far" as it keeps track of that value until the .reduce() is complete.
  • Notice that the second argument that .reduce() takes is the starting value of the accumulator. This may not always be 0!
const numbers = [1, 2, 3, 4, 5]

const sum = numbers.reduce((accumulator, value) => {
    return accumulator + value
  }, 0)

// console.log(sum) will return 15

NOTE The single value returned can be an object or array. Often in examples it is a number or string but you can return anything. Reduce is extremely powerful and all other iterators can be written using it.

  • The .some() method tests whether at least one element in the provided array satisfies the conditions of the provided function. If at least one element in the array satisfies the conditions of the provided function, true is returned. If none of the elements pass the test, false is returned.
const numbers = [1, 2, 3, 4, 5]

const greaterThanThree = array.some((num) => {
    return num > 3
  })

// console.log(greaterThanThree) will return true

Method Chaining & Using Declared Functions

  • When using these array methods we can method chain. So instead of doing:
const numbers = [1, 2, 3, 4, 5]

const mappedNumbers = numbers.map((num) => {
    return num + 1
  })

// console.log(mappedNumbers) will return [ 2, 3, 4, 5, 6 ]

const filteredNumbers = mappedNumbers.filter((num) => {
    return num % 2 === 0
  })

// console.log(filteredNumbers) will return [ 2, 4, 6 ]

We can do:

const numbers = [1, 2, 3, 4, 5]

const filteredAndMappedNumbers = numbers.map((num) => {
    return num + 1
  }).filter((num) => {
    return num % 2 === 0
  })


// console.log(filteredAndMappedNumbers) will return [ 2, 4, 6 ]

Furthermore, we don't have to inline the anonymous functions, we can declare them elsewhere and pass them in:

const numbers = [1, 2, 3, 4, 5]

const add1 = (num) => {
  return num + 1
}

const isEven = (num) => {
  return num % 2 === 0
}

const result = numbers.map(add1).filter(isEven)

// console.log(result) will return [ 2, 4, 6 ]

Lesson Recap

We learned how we can use .forEach() on each item in an array. We also learned about the all-important array methods .map(), .filter(), and .reduce(). We also learned how to use method chaining to more efficiently affect our data.

Resources

u1_lesson_hof's People

Contributors

ben-manning avatar nobodyslackey avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.