I’m learning JavaScript through freeCodeCamp and the way they explained (or rather, didn’t) arrow functions has led to some massive confusion for me.
I am familiar with calling a function using arrow notation like this:
const myFunc = () => "value";
But in one of the later challenges, the code they provided calls a function I have to write using the following code:
findElement([1, 2, 3, 4], num => num % 2 === 0);
Here, the arrow notation is used as a parameter for a function, and not when calling a function. I have no idea what it means.
I managed to write a function that works:
function findElement(arr, func) {
let num;
for(let i = 0; i < arr.length; i++){
num = arr[i];
console.log(num);
if (func(num)) {
return num;
}
}
}
but I don’t understand why it works
3
Answers
I believe it means equal to or greater than.
=>
is the arrow function expressions.It is a compact alternative to a traditional function expression.
You can find out more on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions.
For example, the following function definition:
can be shortened with the
=>
:As stated
=>
is an arrow function – a shorter version of writing a normal function, but with some gotchas.In your following code, the
()
is necessary because the function is taking no parameters…If you had one parameter, then you can lose the brackets (although you don’t have to)… both the following are both valid…
If you had two or more parameters, then you also need the brackets…
As a result in the following code, you are creating an arrow function with a single parameter (
num
) and so it doesn’t need the brackets (these are identical)…The gotchas I mentioned earlier are to do with binding to keywords like
this
,arguments
andsuper
… which you can read more about in the documentation