JavaScript Arrow Function question

I’m currently going through the intermediate JavaScript challenges, and I am seeing a reoccurring solution set up that I am not fully understanding and I’m hoping you can help clarify.
I keep seeing solutions for the challenges similar to this:

const findMyKeys = arr => arr.findIndex(item => item === ‘keys’)
or
const sortSpeciesByTeeth = (arr) => arr.sort((thing1, thing2) => thing1.numTeeth > thing2.numTeeth);

On the surface I understand that this is an arrow function where an array would be taken as a parameter, then a method would be performed involving looping. However, I’m trying to understand this more on a syntax level because I am having trouble figuring out what each part of the code is doing.

I’ve looked through the forum in the sections regarding intermediate JavaScript challenges and read the article you linked back in '17 regarding curried arrow functions, but I still find myself struggling to figure out how to properly write a function like this. I see you all over the forums for this subject, so I’m hoping you are the right person to get a better explanation from.

My current understanding is:

const findMyKeys = is setting up the arrow function with the name
arr => is naming the parameter and setting up the ‘thing to do’ part of the arrow function
arr.findIndex is instructing the ‘thing to do’ to use the findIndex method
(item => item === ‘keys’) this is the part I find most confusing; I know that there is a loop in there, but I don’t understand the inclusion of ‘=>’ as if there is another arrow function within the initial arrow function. And I know that essentially it is saying to loop through each ‘item’ in the array looking for ‘keys’, but I don’t understand what the different parts are doing on a syntax level.

And for the other function:

((thing1, thing2) => thing1.numTeeth > thing2.numTeeth) similarly confuses me in the sense that I understand a loop is being performed checking if thing1 has more teeth than thing2, but unsure of what else it is doing.

I really want to understand this and appreciate any help/explanation you can offer.

Concise body arrow functions are intended for use especially in this instance, a callback function expression. They are only called by the iterator, itself, so do not need all the baggage that comes with a standard function.

array.iterator(callback)

array.iterator(param => param)

The loop is implicit (not obvious) but it is there, only handled internally by the iterator method.

arr.findIndex(item => item === 'keys')

The iterator goes through the array from end to end, until it finds an element that meets with the condition. If the array has fifty elements, the callback is invoked up to fifty times (or less if condition is met).

Arrow functions have some cool features when used in this setting. With only a single parameter we can leave off the parens, and with a single expression in the body we can leave off the braces and the return keyword. This is called, implicit return.

Does this apply only to for loops, or does it work for all loops?
For example, can this function be turned into a concise body arrow function:

const factorial = (num) => {
let newNum = num;
while(num > 1){
num -= 1;
     newNum *= num;
   };
return newNum;
};

Or is it less about the loop and more about it being primarily used for arrays? Since it only seems to being used for arrays in the intermediate JavaScript Challenges, I’m trying to picture where else this could be implemented.

Arrow functions are simplified functions, and may be used in much the same way. They are well suited to callbacks and helper functions. Callbacks are commonly used in Higher Order Functions such as iterators and event listeners.

We can emulate an iterator with a for loop or a while loop but the code is imperative (procedural statements) whereas iterator code is generally expression form.

Don’t confuse arrow functions as having anything to do with loops. They are a different construct. Iterators generally act upon a particular class of object, arrays being the most common. If you look up arrays on MDN you’ll find a complete list of Array methods, the iterators among them.

In your code example above, there is no benefit to using an arrow function since the code is multi-statement. For that purpose the standard function is better suited.

const factorial = function (n) {
    let f = 1
    while (n > 0) {
        f *= n
        n--
    }
    return n
}

This is definitely something I’m going to have to practice more to perfect, but I feel like I have a better understanding of it now.
Thanks a lot for your help.

1 Like

enumerate_and _filter_with_forEach

a = [3, 8, 9, 2, 6, 7, 1, 4, 5]
b = []
a.forEach(function (x, i) {
    if (x % 2) {
        this.push([i, x])
    }
}, b)
b.forEach(x => {
    console.log(x)
})
/* output
[0, 3]
[2, 9]
[5, 7]
[6, 1]
[8, 5]
*/

Above we are using Array.forEach() to both filter and to enumerate the filtered results with their existing index in a. In the first forEach we are forced to use function since we have a this argument. In the latter we could use arrow syntax since we need neither this nor return. The syntax in the second case is by choice, as in, optional. The first case we don’t have a choice.

The point here is to not consider that every callback function is or should be an arrow function. First we write the function in standard form and then determine if we can benefit from arrow syntax. If not, then toss it. Stick to standard form. Don’t make trade-offs with subjective choices. Pick a philosophy and then stick with that. Be consistent in your code.

Errata
The image above was not meant to have the , b argument in the forEach().

Do you find in the industry that arrow functions are the dominant thing being used? Or are standard functions found more often than not with a slow but steady push into seeing more arrow functions?
I ask because, initially I was of the mind that I should put more focus on arrow functions as they are newer than the standard functions, but now I’m realizing I was using arrow functions in many cases where using function may have been the cleanest approach.
Since our conversation, I’m putting more thought into using function vs arrow function so that I can do both better, but my goal is to aim for industry norms so I can have a better chance at succeeding in getting employed.

Can’t speak for industry norms, but on the whole, sensibility is the common element. Arrow functions have their place. They are not a replacement of the standard function form, rather augmenting them. The intended use cases are as lambda to reduce their bulk.

Start by writing in standard form…

Array.filter(function (x) {
    return typeof x === 'number'
})

The above is perfect example of where a lambda can simplify the code, and is a good use case…

 Array.filter(x => typeof x === 'number');

Notice how we remove the bulk of the function expression but keep the same functionality in expression form? This is a sensible implementation of a concise body arrow function.

1 Like