Mapping an Array

Hi everyone! I’m fairly new to Javascript and I’m currently doing the fundamentals course. There is a lesson about mapping through an array with the method “map”. This has a callback function and earlier in the course it was explained that you can use arrow functions to shorten these.
Now I wanted to write down both ways, since I find the “non-arrow-function” way a little easier to understand as of now. However, the result of the code(even though it should do the same) is different. Can somebody explain this? Thanks so much! My code is below.

This is my code:

const items = positiveNumbers.map((n) => “

  • ” + n + “
  • ”);
    console.log(items);

    this leads to this on the console:
    [ ‘

  • 1
  • ’, ‘
  • 2
  • ’, ‘
  • 3
  • ’ ]

    However if I write this:

    const items = positiveNumbers.map(function (value) {

  • ” + value + “
  • ”;
    });

    I get the below in the console:
    [ undefined, undefined, undefined ]

    Why is this? am I doing something wrong? Apprciate any help here! :slight_smile:

    Hi because arrow functions are designed to be concise, they return implicitly in the function body for single expressions, which means we can omit or ‘leave out’ the return statement.

    traditional functions however, we need to explicitly use the return statement if we are returning a value (ie: not producing a side effect like printing to the console)

    So to fix your code you need the return keyword in your function

    1 Like

    Hi there! Thanks so much for the explanation! This fixed it indeed and I will keep it in mind! :slight_smile:

    1 Like

    Hi franzi, also I should have mentioned, we omit the return statement in an arrow function if we only have a single expression. If we have multiple expressions then we need to use curly braces and the return statement:

    for example:

    // Implicit return
    (x, y) => x + y; 
    
    // Explict return
    (x, y) => {
      const sum = x + y;
      const userData = 5
      return sum / userData;
    }
    

    The implicit return is what is called “Syntactic sugar” so we don’t need to be so verbose and can write things more shorter. It can be confusing for beginners like I was at the start but as you start writing and looking at more code it starts to make more sense.

    1 Like

    thanks, this also give me hope haha :slight_smile: