Stuck on the introduction parts of ES6. Help!

Tell us what’s happening:
I started the ES6 recently, but everything is falling apart.
I looked on the hint also but couldn’t understand. I have a lot of questions now.

  1. Why have we named the arrow function as arr when it is used only once?
    Can’t it be done without naming my function like this () => {} ?

  2. Why we aren’t using any variable keyword (var, let or const) with it?
    Is the num a global variable?
    How does it know that by ‘num’ we mean every single item in our Array?

 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);

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions

Arrow functions don’t have a name, same with anon functions (function(){}), in order for them to have a name they have to be stored in a variable or assigned to an object as a “method.”

Also, num and arr aren’t global variables, they’re parameters just like you’d do in regular functions. Parameters don’t require assignment keywords like var/let/const.

It’s a bit weird that squaredIntegers is declared inside the function and then returned immediately afterwards; they could’ve saved code by just returning arr.filter.etceteraetcetera.

Thanks @luishendrix92 I got it.
Can you tell me how filter() function knows that num refers to ever single array-item in the array ?

It’s not that it “knows”, more like, filter loops through each element in the list and sends 3 arguments to the arrow function in the following order:

1- The current item in the loop
2- The index of said item
3- The reference to the original array

If your arrow has more than 3, it will ignore the rest
If it has 2 parameters, it will not receive the original array as reference
If it only has 1 parameter, it will not receive neither the original array nor the current index, just the current item.

You can define your own filter as follows:

function filter(list, predicate) {
  let filtered = []

  for (let i = 0; i < list.length; i++) {
    let currentItem = list[i]

    if (predicate(currentItem, i, list)) {
      filtered.push(currentItem)
    }
  }

  return filtered
}
1 Like