👨🏿‍💻
Learn
  • Learn And The Power Of Community
  • Intro
    • learn-co-curriculum/welcome-to-learn-verified
    • learn-co-curriculum/your-first-lab
    • learn-co-curriculum/environment-setup
  • Intro to tic tac toe
    • matz-readme
    • what-is-a-program?
    • hello world
    • Intro to irb
    • Reading-error-messages
    • Data-types
    • variable
    • Variable-assignment lab
    • String interpolation
    • Interpolation-super-power
    • Welcome to tic tac toe
    • Array
    • Tic tac toe board
    • Intro to methods
    • Puts print and return
    • Intro-to-tdd-rspec-and-learn
    • Methods and arguments
    • Say hello (lab)
    • Methods-default-arguments
    • ttt-3-display_board-example
    • ttt-4-display-board-rb
    • Intro-to-cli-applications
    • Greeting-cli
    • cli-applications in Ruby
    • Ruby-gets-input
    • Tic tac toe move
    • Truthiness-in-ruby-readme
    • booleans
    • conditional (if)
    • ttt-6-position-taken
    • ttt-7-valid-move
    • rspec-fizzbuzz
    • Looping-introduction
    • Loop
    • while-and-until-loop
    • Tic Tac Toe Turn lab
    • looping-while-until lab
    • Tic Tac Toe Play Loop (lab)
    • Tic Tac Toe Current Player (lab)
    • Intro to ruby iterators
    • Nested Arrays
    • Boolean Enumerators
    • Search Enumerators
    • Tic Tac Toe Game Status
    • tic-tac-toe
  • OOP tic tac toe
    • intro to oop
    • Intro-to-classes-and-instances
    • Classes-and-instances-lab
    • Instance-methods
    • Instance-methods-lab
    • Object Attributes
    • object-attributes-lab
    • Object Initialization
    • Object-initialize-lab
    • oop barking dog lab
    • Procedural-vs-oop
    • oop tic tac toe
  • Git and github
    • Intro to Version Control
    • Git Repository Basics
    • Git-basics-quiz
    • Forks-and-clones
    • Git Remotes and Github
    • Git Remotes and Github Codealong
    • Thinking Ahead: GitHub as Career Differentiator
    • Github Pull Requests
    • Git Collaboration
    • Git-collaboration-quiz
    • Git Basics Quiz
  • HTML
    • A-quick-tour-of-the-web
    • The-web-is-made-of-strings
    • What-makes-the-web-possible?
    • html-introduction
    • Your first-html-tag-lab
    • Nested-tags-and-attributes
    • Well-formed-html-document-lab
    • HTML elements types overview
    • Researching-HTML-elements
    • Separation-of-content-and-presentation
  • CSS
    • Introduction-to-css
    • introduction-to-css-code-along
  • Procedural Ruby
    • Regex-what-is-a-pattern
    • Regex-basics
    • Regex-lab
    • Regex-match-scan-grep-methods
    • learn-co-curriculum/method-arguments-lab
    • Method-scope
    • Return Values Lab
    • Debugging-with-pry
    • Method-scope-lab
    • Truthiness-code-challenge
    • If Statements Lab
    • Case-statements
    • Case-statements-quiz
    • Logic and Conditionals Quiz
    • Ternary Operators and Statement Modifiers lab
    • Looping Lab
    • looping-quiz
    • learn-co-curriculum/looping-times
    • countdown-to-midnight lab
    • Array introduction
    • Using Arrays
    • Array-CRUD-lab
    • Array-methods
    • Array-methods-lab
    • Square array lab
    • Collect and Return Values
    • Collect Lab
    • Badges and Schedules Lab
    • Oxford comma lab
    • Deli counter lab
    • Reverse Each Word Lab
    • Yield-and-blocks
    • Each Lab
    • Return from Yield Statements
    • My All? Lab
    • My Find Lab
    • Cartoon Collections Lab
    • Enumerators Code Challenge
    • Prime? Lab
    • Sorting
    • Sorting Lab
    • Introduction to Hashes
    • Using Hashes lab
    • Ruby-symbols
    • Hash iteration
    • Hash Iteration Lab
    • Hash Iteration with Collect
    • Intro to Nested Hashes
    • Building Nested Hashes
    • Building Nested Hashes Lab
    • Nested Hash Iteration
    • Nested Hashes Lab
    • Multitype Collections Lab
    • Iterating over Nested Hashes Codealong
    • Other Hashes Codealong
    • Hashes Manipulation Lab
  • OOP Ruby
    • OO Ruby Video: Object Orientation Overview
    • Object Accessors
    • Instance Variables lab
    • Video Review: Object Properties
    • Meowing Cat
    • Intro to Object Orientation - Ruby
    • oo basics lab
    • OO Basics with Class Constants
    • Self
    • OO School Domain lab
    • OO Counting Sentences lab
    • Class Variables and Methods
    • Class Variables and Methods Lab
    • Remembering Objects
    • Puppy Lab
    • Advanced Class Methods
    • Advanced Class Methods Lab
    • Video Review: Object Models
    • OO Email Parser lab
    • OO Anagram Detector lab
    • OO Cash Register lab
    • Intro to Object Relationships
    • Belongs to Object Lab
    • Has Many Object
    • Has Many Object Lab
    • Collaborating Objects Review
    • Collaborating Objects Lab
    • OO My Pets
    • oo kickstarter lab
    • OO Banking lab
    • Has Many Objects Through
    • Has Many Objects Through Lab
    • Intro to Inheritance
    • Intro to Inheritance Lab
    • Super
    • Super Lab
    • Intro to Modules
    • Intro to Modules Lab
    • Mass Assignment
    • Mass Assignment and Metaprogramming
    • Mass Assignment Lab
    • Custom Errors lab
    • OO Triangle lab
  • Scraping and project
    • Gems and Bundler
    • Scraping
    • Scraping Lab
    • Kickstarter Scraping Lab
    • Video Review: Object Orientation and Scraping
    • OO Ruby Object Orientation Video Review
    • Music Library CLI
    • Video Review: Music Library CLI
    • Tic-tac-toe with AI project
    • Student Scraper
    • CLI Data Gem Portfolio Project
    • CLI Data Gem Walkthrough
    • CLI Data Gem Walkthrough: Creating a CLI Scraper Gem
    • Common Anti-Patterns in CLI Data Gem
    • Student Example 1: Refactoring CLI Gem
    • Student Example 2: Refactoring CLI Gem
  • SQL
    • What is SQL
    • SQL Intro and Installation
    • SQL Database Basics
    • SQL Databases and Text Editors
    • SQL Data Types
    • SQL Inserting, Updating, and Selecting
    • Basic SQL Queries
    • SQL Aggregate Functions
    • SQL Aggregate Functions Lab
    • SQL Bear Organizer Lab
    • Edgar Codd and Table Relations
    • Table Relations
    • SQL JOINS
    • SQL Complex Joins
    • SQL Join Tables
    • Grouping and Sorting Data
    • SQL Joins Review Lectures
    • SQL Crowdfunding Lab
    • SQL Library Lab
    • Pokemon Scraper Lab
  • ORM And Active record
    • Why an ORM is Useful
    • Mapping Ruby Classes to Database Tables
    • Mapping Classes to Tables Lab
    • Mapping Database Tables to Ruby Objects
    • Mapping Database Rows to Objects Lab
    • Updating Records in an ORM
    • Updating Records in an ORM Lab
    • Preventing Record Duplication
    • ORMs Lab: Bringing It All Together lab
    • Dynamic ORMs
    • Dynamic ORMs with Inheritance
    • ActiveRecord Mechanics
    • Translating from ORM to ActiveRecord
    • Intro to Rake
    • Mechanics of Migrations
    • Writing Our Own Migrations
    • Migrations and Active Record Lab
    • ActiveRecord CRUD Lab
    • Advanced Finding Lab
    • ActiveRecord Associations
    • ActiveRecord Associations Lab
    • ActiveRecord Associations Lab II
    • ActiveRecord Associations Video Review
    • ActiveRecord Associations Video Review II
    • Video Review: Aliasing ActiveRecord Associations
    • Video Review: Blog CLI with ActiveRecord and Associations
  • Rack
    • How the Internet Works
    • Increasing Layers of Abstraction
    • Inspecting the Web with Rack (lab)
    • The HTTP Request
    • Dynamic URL Routes
    • Dynamic Web Apps with Rack (lab)
    • Rack Responses Lab
    • Rack Routes and GET Params Lab
    • HTTP Status Codes
    • Dynamic URLs and Status Codes Lab
    • Video Review: How The Web Works, Pt 1
    • Video Review: How the Web Works, Pt 2
  • Html
    • How the Web Works
    • Site Planning
    • HTML Fundamentals
    • HTTP Status Codes
    • video review how the web works pt 1
    • How the Web Works, Part 2: Overview
    • Setting Up a New Site
    • Document Structure
    • Text Formatting
    • HTML Tables
    • Html-images
    • HTML Links
    • Html backing-up changes
    • HTML Validation
    • Quiz - HTML Fundamentals
    • Dev Tools Super Power
    • HTML Lists
    • Html issue bot 9000 (lab)
    • HTML Forms and Iframes
    • HTML Map and Contact Form Code-along
    • HTML5 Media
    • HTML5 Video Embed Code-Along
    • HTML5 Semantic Elements
    • HTML5 Semantic Containers Code-along
    • HTML5 Quiz
  • CSS
    • CSS Fundamentals
    • CSS Styling Code Along
    • My Little Rainbow
    • CSS Kitten Wheelbarrow
    • CSS Graffiti Override Lab
    • CSS Issue Bot 9000
    • Your first deployment
    • The Box Model
    • Layout Types
    • Float
    • Clearfix
    • Centering
    • Column Structure
    • CSS Columns Code Along Exercise (lab)
    • Box Model & Page Layout
    • Using Z Index
    • Positioning
    • ZHW Shoes Layout (lab)
    • Zetsy (lab)
    • CSS Box Style Code Along
    • Animal Save (lab)
    • Building Responsive Sites
    • Intro to Responsive Media
    • CSS Media Queries
    • Working with Responsive Type
    • Responsive layout
    • The Viewport Property
    • Responsive Features Code-Along (lab)
    • Bootstrap Introduction
    • Bootstrap Code-Along
    • Bootstrap Grid System
    • Grid Layout Code-Along
    • Bootstrap Navbar Code-Along
  • Sinatra
    • What is Sinatra?
    • Sinatra From Scratch
    • Using the Shotgun Development Server (lab)
    • Sinatra Basics
    • Sinatra Hello World Basics (lab)
    • Routes in Sinatra
    • Sinatra Routes Lab
    • Intro To MVC
    • Sinatra MVC File Structure (lab)
    • Sinatra Views: Using ERB
    • Sinatra Views (lab)
    • Sinatra Basic Views Lab
    • Sinatra Views Lab II
    • Intro To Capybara
    • Dynamic Routes in Sinatra
    • HTML Forms and Params
    • Passing Data Between Views and Controllers in Sinatra
    • Sinatra Forms Lab
    • Sinatra Yield Readme
    • Integrating Models Sinatra Code-along
    • Sinatra MVC Lab - Pig Latinizer
    • Sinatra Basic Forms Lab
    • Sinatra Forms
    • Nested Forms Readme
    • Sinatra Nested Forms Lab: Pirates!
    • Lab Review-- Sinatra Nested Forms Lab: Pirates
    • Sinatra Nested Forms Lab: Superheroes!
    • Sessions and Cookies
    • Mechanics of Sessions
    • Sinatra Basic Sessions Lab
    • Using Sessions
    • Sinatra and Active Record CRUD
    • Sinatra Activerecord Setup
    • Sinatra ActiveRecord CRUD
    • User Authentication in Sinatra
    • Sinatra Sessions Lab - User Logins
    • Securing Passwords
    • Secure Password Lab
    • Sinatra Authentication- Overview
    • RESTful Routes
    • Restful Routes Basic Lab
    • Sinatra ActiveRecord Associations: Join Tables
    • Using Tux in Sinatra with ActiveRecord
    • ActiveRecord Associations in Sinatra
    • Sinatra Multiple Controllers
    • Sinatra and Active Record: Associations and Complex Forms
    • Sinatra Playlister (lab)
    • Welcome to NYC Sinatra! (lab)
    • Building a Site Generator, Part 1- Overview
    • Building a Site Generator, Part 2- Overview
    • Fwitter Group Project
  • Rails
    • Welcome To Rails
      • Rails Application Basics
      • Rails Static Request
      • Rails Hello World Lab
      • Rails Model View Controller
      • Intro to Rails- Overview
    • Intro to REST
    • Active Record Models and Rails
    • ActiveRecord Model Rails Lab
    • RESTful Index Action Lab
    • Rails Dynamic Request
    • Rails Dynamic Request Lab
    • Rails URL Helpers
    • Rails URL Helpers Lab
    • Rails form_tag
    • Rails form_tag Lab
    • Create Action
    • Create Action Lab
    • Index, Show, New, Create Lab
    • Edit/Update Action
    • form_for on Edit
    • Strong Params Basics
    • form_for Lab
    • Rails Generators
    • CRU with form_for Lab
    • Resource and Scaffold Generator
    • Rails Blog scaffold
    • Todo mvc assets and managing lists
    • Rails Forms Overview
    • ActiveRecord Validations
    • ActiveRecord Validations Lab
    • Validations in Controller Actions
    • Validations In Controller Actions Lab
    • Validations with form_tag
    • Validations with form_for
    • DELETE Forms and Requests
    • Testing in Rails
    • Validations with form_tag
    • CRUD With Validations Lab
    • Join the Fun rails
    • Activerecord lifecycle reading
    • Displaying Associations Rails
    • Active Record Associations Review
    • Forms And Basic Associations Rails
    • Forms And Basic Associations Rails Lab
    • Basic Nested Forms
    • Displaying Has Many Through Rails
    • Displaying Has Many Through Rails Lab
    • Has Many Through Forms Rails
    • Has Many Through Forms Rails Labs
    • Has Many Through in Forms Lab Review- Overview
    • Deep Dive into Nested Forms- Overview
    • Layouts And Templates in Rails
    • Rails Layouts And Templates Lab
    • Simple Partials
    • Simple Partials Lab
    • Partials with Locals
    • Partials with Locals
    • Refresher on MVC
    • Refactoring Views With Helpers
    • Refactoring Views With Helpers Lab
    • Model Class Methods
    • Optimal Queries using Active Record (lab)
    • Routing And Nested Resources
    • Nested Resource Routing Lab
    • Modifying Nested Resources
    • Modifying Nested Resources Lab
    • Namespaced Routes
    • Namespaced Routes Lab
    • Todomvc 2 lists have items
    • TodoMVC 3: Mark Items Complete
    • Todomvc 4 refactoring with partials and helpers
    • Todomvc 5 deleting items
    • Introduction to Authentication and Authorization
      • Cookies and sessions
      • Cookies and Sessions Lab
      • Sessions Controller
      • Sessions Controller Lab
      • Login Required Readme
      • Login Required Lab
      • Using has_secure_password
      • Has_secure_password lab
      • Authentication- Overviewn
      • OmniAuth
      • Omniauth Lab
      • Omniauth review lecture in todomvc
      • Authentication and authorization recap and gems
    • Rails Amusement Park lab
    • How to Find Gems
  • JavaScript
    • Intro to JavaScript
      • JavaScript Data Types
      • JavaScript Data Types Quiz
      • JavaScript Variables
      • JavaScript Comparisons
      • Conditionals
      • Logical Operators
      • Functions
      • Intro to Debugging
      • Intro to Testing
      • JavaScript Basics Quiz
    • Scope
      • Scope chain
      • JavaScript Practice Scope Lab
      • Lexical scoping
      • Errors and Stack Traces
      • Hoisting
    • Arrays And Objects
      • Objects
      • JavaScript: Objects and Arrays Quiz
      • Object Iteration
      • JavaScript Logging
      • Traversing Nested Objects
      • Filter
      • Map
    • Functions Revised
      • First-Class Functions Lab
      • First-Class Functions
      • First-Class Functions Practice
      • First-Class Functions Practice Lab
    • OOP
      • Creating Objects
      • Object Methods and Classes
      • Using Prototypes
      • Using Classes in Javascript
      • JavaScript This Walkthrough
      • This Code-along
      • Bind, Call, and Apply Readme
      • Bind, Call, Apply Lab
      • Object Relations
      • Association Methods in Javascript
      • Class Relations Lab
      • JavaScript Closures and Higher Order Functions
      • Closures Lab
      • JavaScript Arrow Functions
      • Daily Lunch Lab
    • DOM
      • Introduction to the DOM
      • Introduction to the DOM Lab
      • More on the DOM
      • Creating and Inserting DOM Nodes
      • The DOM Is a Tree
      • Listening to Nodes
      • Modify HTML With jQuery
      • Modifying HTML Lab
      • jQuery Selectors
      • Document.ready
      • Acting On Events Lab
      • DOM Quiz
    • Templates
      • Introduction to CSS
      • CSS Quiz
      • CSS Libraries
      • CSS Libraries Lab
      • Intro to Templates
      • Template Engines
      • Template Engines Lab
      • Advanced Templating
      • Advanced Templating Lab
    • Asynchronous JavaScript
      • Intro to XHR Code Along
      • Hitting APIs Lab
      • Advanced AJAX Lab
      • AJAX and Callbacks
      • AJAX and Callbacks Lab
      • REST Refresher
      • REST Quiz
      • Fetch
      • JavaScript fetch() Lab
      • Intro to Mocha
      • Testing with Spies
      • Testing with Mocks and Stubs
  • Rails and JavaScript
Powered by GitBook
On this page
  • Objectives
  • Introducing .forEach()
  • More practice with callbacks
  • .sort() it out!
  • Reduce! Reduce!
  • More practice with functions that return functions
  • Closures
  • Resources
  1. JavaScript
  2. Functions Revised

First-Class Functions Practice

Objectives

  1. Pass callback functions to .forEach() and .sort().

  2. Construct functions that return other functions as a way to cut down on code repetition.

  3. Understand that a function returned by another function has access to any variables from the outer function.

Introducing .forEach()

Prior to the introduction of the for...of statement, .forEach() was the single best way to iterate over all the elements in an array and perform the same action on each. .forEach() is a built-in method available on all JavaScript arrays that accepts one argument: a callback function. The callback function is invoked once for each element in the array, and three arguments are passed to it upon each invocation: the current element, the index of that element within the array, and the array itself. Here's an example:

const callback = function (el, i, arr) {
  console.log('The current element is', el);
  console.log('The index of the current element is', i);
  console.log('The current array is', arr);
  console.log('----------------');
};

['Red', 'Yellow', 'Blue'].forEach(callback);
// LOG: The current element is Red
// LOG: The index of the current element is 0
// LOG: The current array is (3) ["Red", "Yellow", "Blue"]
// LOG: ----------------
// LOG: The current element is Yellow
// LOG: The index of the current element is 1
// LOG: The current array is (3) ["Red", "Yellow", "Blue"]
// LOG: ----------------
// LOG: The current element is Blue
// LOG: The index of the current element is 2
// LOG: The current array is (3) ["Red", "Yellow", "Blue"]
// LOG: ----------------

We can rebuild this same functionality with a for...of statement:

const callback = function (el, i, arr) {
  console.log('The current element is', el);
  console.log('The index of the current element is', i);
  console.log('The current array is', arr);
  console.log('----------------');
};

const myForEach = function (arr, cb) {
  for (const el of arr) {
    cb(el, arr.indexOf(el), arr);
  }
};

myForEach(['Red', 'Yellow', 'Blue'], callback);
// LOG: The current element is Red
// LOG: The index of the current element is 0
// LOG: The current array is (3) ["Red", "Yellow", "Blue"]
// LOG: ----------------
// LOG: The current element is Yellow
// LOG: The index of the current element is 1
// LOG: The current array is (3) ["Red", "Yellow", "Blue"]
// LOG: ----------------
// LOG: The current element is Blue
// LOG: The index of the current element is 2
// LOG: The current array is (3) ["Red", "Yellow", "Blue"]
// LOG: ----------------

However, the benefit of .forEach() is that it's already available on every array in JavaScript — we don't need to build out anything additional. .forEach() provides a wonderfully compact, readable syntax for invoking a function on every member of an array. It's a powerful tool that makes it easier for us to perform complex operations in just a few lines of code.

More practice with callbacks

.forEach() is one of the most common constructs for learning about callbacks in JavaScript because it's relatively easy to understand. We have a collection of elements and want to execute a function once for every element, so we pass a callback function to .forEach() and let it handle the implementation. That's the gist of callbacks: we create a function but delegate control of when it should be invoked to another function. The callback function doesn't care when it is invoked; it just knows that, at some later point, it may be invoked, perhaps after some other processes have completed or some data that it relies upon becomes available. Callbacks are one of the most important concepts that you'll employ throughout your JavaScript career. For some extra practice, let's take a look at the .sort() method available on all JavaScript arrays.

.sort() it out!

The .sort() method is a handy little helper for sorting an array in-place. That means that we're destructively rearranging the elements in the original array; we aren't sorting the elements and storing them in a new array. The method works by coercing each element into a string and comparing the Unicode value of each character. The letter 'A' has a lower Unicode value than 'B', so, if a simple alphabetic ordering is what you're after, you're in good shape:

const guestList = ['Kate', 'Jonas', 'Lisa', 'Jan', 'Kaitlin'];

guestList.sort();
// => ["Jan", "Jonas", "Kaitlin", "Kate", "Lisa"]

guestList;
// => ["Jan", "Jonas", "Kaitlin", "Kate", "Lisa"]

However, things get a little thorny if the strings aren't uniformly capitalized:

const guestList = ["jan", "Jonas", "kaitlin", "Kate", "Lisa"];

guestList.sort();
// => ["Jonas", "Kate", "Lisa", "jan", "kaitlin"]

The Unicode values for uppercase letters are all lower than those for lowercase letters, so .sort() orders all of the title-case strings first and then all of the lowercase strings after. This is the method's default sorting behavior, and it's a bit annoying. However, lucky for us, we can customize it according to our needs by passing in a callback function.

.sort() with a callback

The callback function will be invoked once per comparison, and it needs to accept two arguments — the two elements that it's being asked to compare:

guestList.sort(function (a, b) {
  // Comparison code in here.
});

The comparison function must return one of three values:

  • If a should come before b in the new ordering, return a negative number.

  • If a and b are equal, return 0.

  • If a should come after b in the new ordering, return a positive number.

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. ... Syntax referenceStr.localeCompare(compareString) ... Return value A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.

That's exactly what we need! Now let's fill out our callback to correctly sort strings in a case-insensitive manner:

guestList.sort(function (a, b) {
  return a.localeCompare(b);
});
// => ["jan", "Jonas", "kaitlin", "Kate", "Lisa"]

Woohoo! We can even make that a bit cleaner by splitting the callback out into its own variable:

const comparator = function (a, b) {
  return a.localeCompare(b);
};

guestList.sort(comparator);
// => ["jan", "Jonas", "kaitlin", "Kate", "Lisa"]

Nice. But what if we're sorting an array of numbers instead of strings? The default comparison algorithm won't work:

const primes = [13, 7, 17, 2, 5, 3];

primes.sort();
// => [13, 17, 2, 3, 5, 7]

The .sort() method coerces the numbers into strings and then compares each character. The first character of '17' is '1', which has a lower Unicode value than the first (and only) character of '2'. Instead of relying on the default algorithm, let's pass in a callback that correctly sorts our numbers in ascending order:

const numberSorter = function (num1, num2) {
  return num1 - num2;
};

primes.sort(numberSorter);
// => [2, 3, 5, 7, 13, 17]

If num1 is larger than num2, the subtraction operation will return a positive number, which tells .sort() to reverse the order of num1 and num2 in the array. If num1 - num2 returns a negative number or 0, .sort() knows to not mess with the ordering.

Reduce! Reduce!

In the world of programming, we often work with arrays of similar elements. Sometimes, we need to aggregate a result from those elements — perhaps summing an array of numbers or concatenating an array of strings into one long string. In other words, we want to reduce the array to a single, ultimate value. For example, imagine that we have a series of products in a shopping cart, and we'd like to know the total price of all items in the cart:

const products = [
  { name: 'Head & Shoulders Shampoo', price: 4.99 },
  { name: 'Twinkies', price: 7.99 },
  { name: 'Oreos', price: 6.49 },
  { name: 'Jasmine-scented bath pearls', price: 13.99 }
];

We can create a function that accepts the array of products, initializes a starting value (totalPrice), and then iterates over the passed-in products array, adding each product's price to the sum stored in totalPrice:

const getTotalAmountForProducts = function (products) {
  let totalPrice = 0;

  products.forEach(function (product) {
    totalPrice += product.price;
  });

  return totalPrice;
};

getTotalAmountForProducts(products);
// => 33.46

That's all well and good, but then what if we actually want to reduce the products array of objects to a simple array that just contains the product names as strings? We definitely can't use our getTotalAmountForProducts() function — we'll have to create a new one:

const gatherProductNames = function (products) {
  const names = [];

  products.forEach(function (product) {
    names.push(product.name);
  });

  return names;
};

gatherProductNames(products);
// => ["Head & Shoulders Shampoo", "Twinkies", "Oreos", "Jasmine-scented bath pearls"]

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. ... Syntax arr.reduce(callback[, initialValue]) ... Return value The value that results from the reduction.

The method takes two arguments, a callback function that will reduce each array element into a single, ultimate value and the initial value that the reduction should start from. For example, if we needed to sum an array of numbers but, instead of starting from 0, we wanted to start counting from 1000, we could pass 1000 in as the initial value.

The callback function accepts four arguments:

  1. The reduced total as it currently stands (or the initial value if nothing's been reduced yet).

  2. The current element that's to be reduced.

  3. The index of the current element within the array.

  4. The entire array.

Let's take .reduce() for a spin:

const reduceProductNames = function (agg, el, i, arr) {
  console.log('The aggregate up to this point is:', agg);
  console.log("The current element's name is:", el.name);
  console.log('The index of the current element is:', i);
  console.log('----------------');

  return [...agg, el.name];
};

products.reduce(reduceProductNames, []);
// LOG: The aggregate up to this point is: []
// LOG: The current element's name is: Head & Shoulders Shampoo
// LOG: The index of the current element is: 0
// LOG: ----------------
// LOG: The aggregate up to this point is: ["Head & Shoulders Shampoo"]
// LOG: The current element's name is: Twinkies
// LOG: The index of the current element is: 1
// LOG: ----------------
// LOG: The aggregate up to this point is: (2) ["Head & Shoulders Shampoo", "Twinkies"]
// LOG: The current element's name is: Oreos
// LOG: The index of the current element is: 2
// LOG: ----------------
// LOG: The aggregate up to this point is: (3) ["Head & Shoulders Shampoo", "Twinkies", "Oreos"]
// LOG: The current element's name is: Jasmine-scented bath pearls
// LOG: The index of the current element is: 3
// LOG: ----------------
// => ["Head & Shoulders Shampoo", "Twinkies", "Oreos", "Jasmine-scented bath pearls"]

const reduceProductPrices = function (agg, el, i, arr) {
  console.log('The aggregate up to this point is:', agg);
  console.log('The index of the current element is:', i);
  console.log("The current element's price is:", el.price);
  console.log('----------------');

  return agg + el.price;
};

products.reduce(reduceProductPrices, 0);
// LOG: The aggregate up to this point is: 0
// LOG: The index of the current element is: 0
// LOG: The current element's price is: 4.99
// LOG: ----------------
// LOG: The aggregate up to this point is: 4.99
// LOG: The index of the current element is: 1
// LOG: The current element's price is: 7.99
// LOG: ----------------
// LOG: The aggregate up to this point is: 12.98
// LOG: The index of the current element is: 2
// LOG: The current element's price is: 6.49
// LOG: ----------------
// LOG: The aggregate up to this point is: 19.47
// LOG: The index of the current element is: 3
// LOG: The current element's price is: 13.99
// LOG: ----------------
// => 33.46

If we take out our verbose logging that's just helping us visualize what's happening inside .reduce(), the method is a delightfully extensible way to reduce an array to a single value:

const stringify = function (agg, el, i, arr) {
  let stringifiedElement = el.name + ' is $' + el.price + '. ';

  if (i === arr.length - 1) {
    stringifiedElement += 'The total price is $' + (agg.totalPrice + el.price) + '.';

    return agg.string + stringifiedElement;
  }

  return {
    string: agg.string + stringifiedElement,
    totalPrice: agg.totalPrice + el.price
  };
};

products.reduce(stringify, { string: '', totalPrice: 0 });
// => "Head & Shoulders Shampoo is $4.99. Twinkies is $7.99. Oreos is $6.49. Jasmine-scented bath pearls is $13.99. The total price is $33.46."

We managed to reduce all the information in the products array of objects down to a single string!

More practice with functions that return functions

const franceTax = function (item, priceInCents) {
  const formattedPrice = '$' + (priceInCents / 100).toFixed(2);

  const exemptItems = ['wine', 'macaron', 'baguette', 'croissant'];
  const exempt = exemptItems.indexOf(item.toLowerCase()) > -1;

  const taxRate = 0.15;
  const taxDue = exempt ? 0 : priceInCents * taxRate / 100;
  const formattedTaxDue = '$' + taxDue.toFixed(2);

  console.log(`In France, ${item} costs ${formattedPrice}.`);
  console.log('That item', exempt ? 'is' : 'is not', 'exempt from taxation.');
  console.log(`The total tax due is: ${formattedTaxDue}.`);
};

const canadaTax = function (item, priceInCents) {
  const formattedPrice = '$' + (priceInCents / 100).toFixed(2);

  const exemptItems = ['maple syrup', 'poutine', 'kindness'];
  const exempt = exemptItems.indexOf(item.toLowerCase()) > -1;

  const taxRate = 0.125;
  const taxDue = exempt ? 0 : priceInCents * taxRate / 100;
  const formattedTaxDue = '$' + taxDue.toFixed(2);

  console.log(`In Canada, ${item} costs ${formattedPrice}.`);
  console.log('That item', exempt ? 'is' : 'is not', 'exempt from taxation.');
  console.log(`The total tax due is: ${formattedTaxDue}.`);
};

const mexicoTax = function (item, priceInCents) {
  const formattedPrice = '$' + (priceInCents / 100).toFixed(2);

  const exemptItems = ['queso', 'futbol', 'tequila', 'avocado'];
  const exempt = exemptItems.indexOf(item.toLowerCase()) > -1;

  const taxRate = 0.05;
  const taxDue = exempt ? 0 : priceInCents * taxRate / 100;
  const formattedTaxDue = '$' + taxDue.toFixed(2);

  console.log(`In Mexico, ${item} costs ${formattedPrice}.`);
  console.log('That item', exempt ? 'is' : 'is not', 'exempt from taxation.');
  console.log(`The total tax due is: ${formattedTaxDue}.`);
};

franceTax('Big Mac', 249);
// LOG: In France, Big Mac costs $2.49.
// LOG: That item is not exempt from taxation.
// LOG: The total tax due is: $0.37.

franceTax('wine', 499);
// LOG: In France, wine costs $4.99.
// LOG: That item is exempt from taxation.
// LOG: The total tax due is: $0.00.

canadaTax('kindness', 0);
// LOG: In Canada, kindness costs $0.00.
// LOG: That item is exempt from taxation.
// LOG: The total tax due is: $0.00.

mexicoTax('tacos al pastor', 350);
// LOG: In Mexico, tacos al pastor costs $3.50.
// LOG: That item is not exempt from taxation.
// LOG: The total tax due is: $0.17.

It's really the same function repeated three times, with three small dynamic pieces:

  • The name of the country.

  • The tax rate.

  • The list of exempt items.

Closures

We can easily decouple those three customizations from the rest of the logic that remains consistent across all three functions. In fact, we can create a function that assembles new tax calculating functions for us! Let's take a look:

const newTaxFunction = function (countryName, taxRate, ...exemptItems) {
  return function (item, priceInCents) {
    const formattedPrice = '$' + (priceInCents / 100).toFixed(2);
    const exempt = exemptItems.indexOf(item) > -1;
    const taxDue = exempt ? 0 : priceInCents * taxRate / 100;
    const formattedTaxDue = '$' + taxDue.toFixed(2);

    console.log(`In ${countryName}, ${item} costs ${formattedPrice}.`);
    console.log('That item', exempt ? 'is' : 'is not', 'exempt from taxation.');
    console.log(`The total tax due is: ${formattedTaxDue}.`);
  };
};

Our newTaxFunction() function can accept two or more arguments. After the first two arguments, every subsequent argument will be captured in the ...exemptItems spread parameter, which leverages the spread operator introduced in ES2015. Our function returns a function, but the returned function still has access to all variables declared in its outer environment, including countryName, taxRate, and exemptItems. Because it retains access to these variables even after newTaxFunction() has finished executing, we say that the returned function has closed over those variables — it has formed a closure.

We can invoke newTaxFunction() three times, passing in a different set of arguments each time. Each invocation will create an entirely separate closure that retains access to the set of arguments passed in for that particular invocation. Let's see it in action:

const franceTax = newTaxFunction('France', 0.15, 'wine', 'macaron', 'baguette', 'croissant');

const canadaTax = newTaxFunction('Canada', 0.125, 'maple syrup', 'poutine', 'kindness');

const mexicoTax = newTaxFunction('Mexico', 0.05, 'queso', 'futbol', 'tequila', 'avocado');

canadaTax('poutine', 599);
// LOG: In Canada, poutine costs $5.99.
// LOG: That item is exempt from taxation.
// LOG: The total tax due is: $0.00.

canadaTax('futbol', 1999);
// LOG: In Canada, futbol costs $19.99.
// LOG: That item is not exempt from taxation.
// LOG: The total tax due is: $2.50.

mexicoTax('Big Mac', 199);
// LOG: In Mexico, Big Mac costs $1.99.
// LOG: That item is not exempt from taxation.
// LOG: The total tax due is: $0.10.

franceTax('macaron', 149);
// LOG: In France, macaron costs $1.49.
// LOG: That item is exempt from taxation.
// LOG: The total tax due is: $0.00.

We invoke newTaxFunction(), pass in our arguments, and store the returned function in a variable, e.g., canadaTax. The canadaTax variable thereafter contains a reference to a function that accepts two arguments, an item and a priceInCents. Take a look:

canadaTax;
// => ƒ (item, priceInCents) {
//        const formattedPrice = '$' + (priceInCents / 100).toFixed(2);
//        const exempt = exemptItems.indexOf(item) > -1;
//        const taxDue = exempt ? 0 : priceInCents * taxRate / 10…

Nowhere in that function is countryName, taxRate, or exemptItems defined, but we still have access to the values that were passed to newTaxFunction() when it was invoked. Aren't closures amazing?!

Resources

  • Array

  • String

PreviousFirst-Class FunctionsNextFirst-Class Functions Practice Lab

Last updated 5 years ago

Since we're comparing strings, this sounds like a job for .localeCompare()! From the :

It's kind of annoying to have to create an entirely new function every time we want to change what we're aggregating inside the .forEach() iteration. Instead of hard-coding it, wouldn't it be nice to extract that logic out into a callback function? Well, thanks to JavaScript's built-in .reduce() method for arrays, we can! Here's the on .reduce():

As a final exercise, you've been onboarded to the Flatbook team tasked with internationalizing some of the tax calculators used by the finance team. When a Flatbook employee goes abroad on a business trip, they track expenses and submit receipts upon their return. The engineering team created a simple tool to help the finance team calculate tax and remember which items are tax-free in a certain country. However, it's currently not very :

View on Learn.co and start learning to code for free.

MDN documentation
MDN documentation
DRY
.forEach()
.sort()
.reduce()
.localeCompare()
StackOverflow — How do JavaScript closures work?
First-Class Functions Practice
Bubble sort!
And that, my friend, is what they call closure.