skip to Main Content

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


  1. I believe it means equal to or greater than.

    Login or Signup to reply.
  2. => 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:

    let f = function(arg1, arg2, ...) {
      return true;
    };
    

    can be shortened with the =>:

    let f = (arg1, arg2, ...) => true;
    
    Login or Signup to reply.
  3. 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…

    const myFunc = () => "value";
    console.log(myFunc()); // Results in "value"
    

    If you had one parameter, then you can lose the brackets (although you don’t have to)… both the following are both valid…

    const myFunc = myArg => "value " + myArg;
    const myFunc = (myArg) => "value " + myArg;
    console.log(myFunc("a")); // Result in "value a";
    

    If you had two or more parameters, then you also need the brackets…

    const myFunc = (myArg1, myArg2) => "value";
    const myFunc = (myArg1, myArg2, myArg3) => "value";
    

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

    findElement([1, 2, 3, 4], num => num % 2 === 0);
    findElement([1, 2, 3, 4], (num) => num % 2 === 0);
    

    The gotchas I mentioned earlier are to do with binding to keywords like this, arguments and superwhich you can read more about in the documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search