Help Understanding: ES6: Write Higher Order Arrow Functions

Hello!

I need some real help understanding the solution (https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions/)

SOLUTION SPOILER BELOW

const squareList = (arr) => {
      "use strict";
      const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );
      return squaredIntegers;
    };

    // test your code
    const squaredIntegers = squareList(realNumberArray);
    console.log(squaredIntegers);

I don’t know where ‘num’ is coming from here and can’t wrap my brain around it:

const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );

To my understanding, the function takes an array (arr), filters it so:

  • Number is greater than zero, AND
  • Remainder is taken from num divided by parseInt(num), and must be 0 to pass the check. (5.4 % 5.0 != 0, so it wouldn’t pass the check).

then maps that to a new array, assigned to squaredIntegers via constant.

I believe I have that right, BUT I’m not sure where the num parameter is coming from and what is actually being passed through this function. (Not really visualizing the code from start to finish). Second, I don’t under

Then I also don’t understand why we are using the ‘const’ keyword to declare ‘squaredIntegers’, returning that variable, than updating at again with ‘const’. I didn’t think that was possible. (It obviously is, I’m just not understanding)

Any help is greatly appreciated!

  1. const: yes, this will throw an error:
const a = 3;
const a = 4; // Duplicate declaration "a"
  1. but if const are in different scopes, ie bracket {}, then you have 2 different a!
const a = 3;

function foo() {
  const a = 42; // this a is another a living just within these brackets -> no error
}
// here a is again = 3 (first a)

see eg:
https://www.w3schools.com/js/js_let.asp
https://www.w3schools.com/js/js_const.asp

You could play around in a codepen then things come clearer

Maybe you come from PHP where it is NOT allowed to redefine a constant in another scope.

num - Look at a simpler version:

const b = [1,2,3,4].filter( (num) => num>2 )
console.log(b); // [3, 4]

You have an array that is filtered. filter() iterates through each element in that array.
And assigns each element to num.

see eg:

1 Like

Awesome - this helps tremendously and makes since. I was missing variable scope, and now see where the num parameter is coming from. Thanks a ton!

And yes, I come from PHP. Haha.