First-Class Functions Practice
Objectives
Pass callback functions to
.forEach()
and.sort()
.Construct functions that return other functions as a way to cut down on code repetition.
Understand that a function returned by another function has access to any variables from the outer function.
Introducing .forEach()
.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:
We can rebuild this same functionality with a for...of
statement:
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!
.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:
However, things get a little thorny if the strings aren't uniformly capitalized:
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
.sort()
with a callbackThe 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:
The comparison function must return one of three values:
If
a
should come beforeb
in the new ordering, return a negative number.If
a
andb
are equal, return0
.If
a
should come afterb
in the new ordering, return a positive number.
Since we're comparing strings, this sounds like a job for .localeCompare()
! From the MDN documentation:
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:
Woohoo! We can even make that a bit cleaner by splitting the callback out into its own variable:
Nice. But what if we're sorting an array of numbers instead of strings? The default comparison algorithm won't work:
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:
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:
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
:
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 name
s as strings? We definitely can't use our getTotalAmountForProducts()
function — we'll have to create a new one:
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 MDN documentation on .reduce()
:
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:
The reduced total as it currently stands (or the initial value if nothing's been reduced yet).
The current element that's to be reduced.
The index of the current element within the array.
The entire array.
Let's take .reduce()
for a spin:
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:
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
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 DRY:
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:
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:
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:
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
String
View First-Class Functions Practice on Learn.co and start learning to code for free.
Last updated