Yes, this is confusing when you first start seeing this.
num => num % 2 === 0
That is an ES6 thing, called a “fat arrow function” or just an “arrow function”. It is (kinda) the same as writing:
function(num) {
return num % 2 === 0;
}
It is a function that returns true
if num is divisible by 2. There are slight differences in writing it as a “normal” function or as an arrow function, but they don’t matter in this case.
Consider the following:
function findString(arr, func) {
for (let i = 0; i < arr.length; i++) {
if (func(arr[i])) {
return arr[i];
}
}
return 'no string found';
}
findString([1, true, 'apple', null], el => typeof el === 'string');
// apple
It is similar and returns the first element that is a string.
We pass findString and array and a function to test if it is a string. The function applies that passed function to each element and returns the first element that passes the test (returns true
from the test function).
We could also have written:
function findString(arr, func) {
for (let i = 0; i < arr.length; i++) {
if (func(arr[i])) {
return arr[i];
}
}
return 'no string found';
}
findString([1, true, 'apple', null], function(el) { return typeof el === 'string'});
// apple
That does basically the same thing, just with a “normal” function. In both these cases, we are passing an anonymous (unnamed) function that we just create and pass into the findString.
We could have also used a named function. For example:
function findString(arr, func) {
for (let i = 0; i < arr.length; i++) {
if (func(arr[i])) {
return arr[i];
}
}
return 'no string found';
}
function isAString(el) {
return typeof el === 'string';
}
findString([1, true, 'apple', null], isAString);
// apple
or with an arrow function:
function findString(arr, func) {
for (let i = 0; i < arr.length; i++) {
if (func(arr[i])) {
return arr[i];
}
}
return 'no string found';
}
const isAString = el => {
return typeof el === 'string';
}
findString([1, true, 'apple', null], isAString);
// apple
Or with a simplified arrow function, with an implied return:
function findString(arr, func) {
for (let i = 0; i < arr.length; i++) {
if (func(arr[i])) {
return arr[i];
}
}
return 'no string found';
}
const isAString = el => typeof el === 'string';
findString([1, true, 'apple', null], isAString);
// apple
All these do the same thing, the only difference is how we’re defining the function that we’re passing into findString.
Arrow functions are very common in modern JavaScript and are probably more common than “normal” functions. There are usually (but not always) better. There are some slight differences that you can read about here.
On aspect of JavaScript is that functions are “first class citizens” and can be assigned to variables and/or passed around to other functions. You can have functions that accept functions and return other functions. It’s weird at first but very powerful.
Try to understand how each of my examples are basically doing the same thing.
Let us know if there is any other confusion.