Help with Arrow Functions exercise!

Hi!

I have been stuck for a good while with an exercise, I also started re-learning in www.w3schools.com about arrow functions in order to find some explanation for the following code, but have not found any explanation for it!

This is the code:

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];
const squareList = (arr) => {
  "use strict";
  // change code below this line
  const squaredIntegers = arr.filter((num)=>num>0&& num % parseInt(num)===0).map((num)=>Math.pow(num,2));

  // change code above this line
  return squaredIntegers;
};
// test your code
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

My doubts are the following, where does the “num” variable come from? IF it is a parameter, how does JavaScript “know” that with “num”, it is the numbers in the array?

I appreciate any help provided.

It’s just a different way to write functions:

function someFunction(aParameter) {
 //do stuff
}

const someFunction = (aParameter) => {
   //do stuff
}

The big difference with the arrow syntax is that you can return a value implicitly

const someFunction = () => "Return this string";  // Don't need a return keyword!

// Same as

function someFunction () {
    return "Return this string";
}

You might also want to take a look at this:

:slight_smile:

1 Like

The array methods will each pass certain parameters to your provided callback in a certain order. filter() will loop through your array and for each element will pass to your callback…

  1. that current element
  2. the index of that element
  3. the entire array

These get passed whether you use them or not. In the case of your filter callback function you are only using the first parameter - the current element - and you have named it “num” in your callback.

const myArray = [5, 10, 15];

const isOdd = myArray.filter(function(elem, index, array) {
	console.log(elem, index, array);
	return elem % 2 !== 0;
});

console.log(isOdd);


/*output
5 0 [ 5, 10, 15 ]
10 1 [ 5, 10, 15 ]
15 2 [ 5, 10, 15 ]
[ 5, 15 ]
*/

Abpve I have named that first parameter ‘elem’ in my callback

1 Like