Finding a Good Deal explainer

.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

15 Likes

The part I don’t understand is how the test exactly works for the comparisons. I get the premise but not how the code plays out, specifically the equals after the max or min at the beginning of the operation, that only “value” follows “?” as the Then outcome for a true “If” test, and then how “min” by itself as the false test outcome means anything. Does anything. I get THAT it keeps the value of min as min going forward instead of changing to the value just compared with it. I just don’t get how so or why the coding language is so minimal there. Probably for efficiency but I’m trying to retain this and I’m finding it a bit more difficult because of that.

Thank you. I hope that all makes sense. Please ask for clarification if not.

3 Likes

Hey there, great question!

Ternaries are popular because they can do in 1 line of code what an if…else statement can do in 5 or 6, which is a useful shortcut that can make the work of writing code a bit faster. The tradeoff is that ternaries can sometimes be a bit miserable to read.

Let’s take a look at one of the ternaries in this puzzle:

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

Let’s say that max is 5, and we call the function with 6 as an argument, like this:
compareToMaximum(6)

The ternary inside the function will check:

max = (is 6 > 5) ? 6 : 5;

Think of the max = at the beginning of the line as reaching a long arm over the test. If the test is true, the max = will grab the value after the ?. If the test is false, it will grab the value after the :

Hope this makes sense! Let me know if you have any further questions.

Ben

12 Likes

It does make sense. That answer will do for my current needed level of understanding.

Thanks :slightly_smiling_face:

3 Likes

what is the difference between .foreach () and .filter (), both of them seem to have the same way of working, looping to the aray and using the callback function

3 Likes

Good question.

`.filter()’ is a way to apply a test to every element in an array and return the elements that pass into a new array.

For example, taking an array of mixed numbers and filtering the even numbers into their own array:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let evenNumbers = numbers.filter(num => num % 2 === 0);
// the % operator finds the remainder after division of one number by another

The .forEach() method runs a callback function with each element as an argument, but doesn’t return anything, so you wouldn’t use it to define a new variable like you would with .filter().

For example, you can use it to print every element in an array like this:

['alpha', 'beta', 'charlie'].forEach(word => console.log(word));

Hope that helps! Let me know if you have any more questions.
Ben

7 Likes

I am little confused with this line,

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

is it declaring max/min = 0; or picking 0th element from flightprices array. Need help.

2 Likes

Hey there, both of the variables are initially set to the first element (at index 0) of the flightPrices array.

Later in the code, we use the compareToMinimum and compareToMaximum functions with .forEach to figure out what the actual min and max values are, but to start, we just set their values to the first element.

Hope this clarifies things! Let me know if you have any further questions.
Ben

7 Likes
var flightprices = ['200','278','470','420','1024']

var max = flightprices[0];

var min = flightprices[0];

function compareMaxv(value){

   max = value>max?value:max;

};

function compareMinv(value){

  min = value<min?value:min;

};

console.log(flightprices.join())

flightprices.forEach(compareMaxv)

flightprices.forEach(compareMinv)

console.log("Maximum:" + max)

console.log("Minimum:" + min)

Help:
o/p
[Running] node “c:\Users\Ganesh R\Desktop\ganesh\forEach.js”
200,278,470,420,1024
Maximum:470
Minimum:1024

what is the problem with code??
please anyone explain!!

Thanks,
th3 j35t3r

2 Likes

Hey there, it looks like you’ve entered the numbers in the flightPrices array as strings of text, instead of numbers.

Using the < or > operator with strings means it will compare the strings as if it’s checking dictionary order. In fancy terms, this is called a “lexicographical comparison”.

For example: 'cat' is less than 'dog' because 'c' is less than 'd'. '1024' is less than '200' because the string '1' is less than the string '2'.

Change your array to store numbers, like this:

var flightPrices = [200, 278, 470, 420, 1024]

Hope this helps!
Ben

7 Likes

Hi,

How would you write this code without using the .foreach to loop through? Could you do it using both options (for var of flightprices) and (let i = 0; i < flightprices.length; i++)? If so could you please write the code?

Thank you.

1 Like

Yeah, you could get the same output with different methods of iteration, whether you use a for loop, classic for loop, or Array.forEach(), like this:


// these all do the same thing:

// for of loop:
for (let flight of flightPrices) {
    compareToMaximum(flight);
}

// classic for loop:
for (let i = 0; i < flightPrices.length; i++) {
    compareToMaximum(flightPrices[i]);
)

// Array.forEach():
flightPrices.forEach(compareToMaximum)

Since Array.forEach() was added to JavaScript in 2015, it’s become very popular because of how easy it is for humans to read. Code readability makes it easier for teams of programmers to work together.

Hope this helps!
Ben

3 Likes

what will be exact difference between the .filter function and .foreach function
Bcoz both functions give result based on what is declared in a function cal ???
do this both functions are same

1 Like

what will be exact difference between the .filter function and .foreach function
Bcoz both functions give result based on what is declared in a function cal ???
do this both functions are same

1 Like

Hello there
it seems the web version is not optimized as its hiding or truncating part of the console.log , leading to confusion.
you should remove the scroll bar and add a line break to the console.log(flightprice); result as I’ve spent some time trying to understand why the console.log min doesnt look like to return the smallest value or the array
see screenshot to compare android version VS desktop version

Thanks for confirming that.forEach() is similar to for… of loop. I was thinking what’s the difference between these two and why they exist if they do the same job.

Hi Pankaj,
This question was already asked and answered above. Here is the link of the same Finding a Good Deal explainer
I hope it helps.
Abdulla

1 Like

hey thanks for the suport…

1 Like

How the program exactly finds the value ? In the compare to maximum function because we didn’t declared anything, like value = flight prices then how the program identify the value we declared??

There is a part of this I don’t understand, the initial max value is the first element in the array(Lets say its 200). When the compareToMaximum function iterates through the flightPrices array and starts at the first element in the array, what does the max value give us true or false;
value=200
initial max= 200
max= value>max?value:max;
max=200>200?
How does it evaluate this? Is it as true or false