Finding a Good Deal explainer

#1

The aim of this puzzle: Use the `.forEach()` method to find the mininum value of the `flightPrices` array.

Walkthrough of the solution: The `max` and `min` variables start out storing the 1st number in the array. These need to be updated to the largest and smallest values in the array. This can be done using the `compareToMaximum` and `compareToMinimum` functions. The `compareToMaximum` function takes a value and checks if it’s larger than the current `max` value. If it is, then `max` gets updated to that new value, otherwise it stays the same. `compareToMinimum` does a similar thing but checking if the value is smaller than the current `min`. All that needs to happen is run all the values of the array through the 2 functions.

Instead of a For Loop, the `.forEach()` method can be used. When `.forEach()` is applied to an array, each element of the array is passed into the callback function given to `.forEach()`. If you use `flightPrices.forEach(compareToMinimum)`, then each of the elements of the `flightPrices` array will be used as the input for `compareToMinimum()`. That `compareToMinimum()` function will update the value of the `min` variable.

Sample code solution:
(Tap below to reveal)

``````import { flightPrices } from 'grasshopper.travel';

let max = flightPrices[0];
let min = flightPrices[0];

function compareToMaximum(value) {
max = value > max ? value : max;
}

function compareToMinimum(value) {
min = value < min ? value : min;
}

console.log(flightPrices);

flightPrices.forEach(compareToMaximum);
console.log('Maximum: ' + max);

flightPrices.forEach(compareToMinimum);
console.log('Minimum: ' + min);
``````

JavaScript Concepts: Callback Functions, Calling Functions, Code Block (function), `console.log()`, Conditionals (ternary statement), `.forEach()`, `import`

#3

This app makes me something like
‘I understand Spanish but cannot speak’

#4

`.forEach()` is similar to a `for...of` loop.

``````flightPrices.forEach(compareToMaximum);
``````

is the same as

``````for (let element of flightPrices) {
compareToMaximum(element);
}
``````

If you just want to run each value in an array through a function, `.forEach()` is a way you can do it with a little less code.

–Frankie