How to use an if statement in an array map function?

Here is how my example code currently looks: https://jsfiddle.net/pwb7t5hf/10/

    const sizes = [
      36,37,38,39,40
    ]
    const allSizes = sizes.map(size => (
          if(size > 38) {
          return size++;
          }
else {
return size;
}

          
        ));
    
        console.log(allSizes);

The debugger gives me bag that if is an unexpected token.

Would appreciate some help :)

PS: I am aware, that this is not a good functional way but I am a bit stuck how to do that the functional way :). So I thought I would solve it, for now, this way.

Posted Jul 24, 2018, 5:06 PM UTC · edited

04
Charles_Stover•

Wrap the function body in curly braces, not parenthesis.

size => { // here
  if (...) {
    return ...;
  }
  else {
    return ...;
  }
} // and here
5
Asha200•

You've surrounded your function body with parentheses, when you should've used curly braces.

Instead of

sizes.map(size => (
  ...
));

You should've used:

sizes.map(size => {
  ...
});

You could use parentheses if they were surrounding an expression, but in your case, you had if and return present, which are statements. Also, you forgot to return a value in the case that a particular size is less than or equal to 38.

Here's a working solution:

const allSizes = sizes.map(size => {
  if (size > 38) {
      return size++;
  }
  return size;
});

Or you could use the ternary operator:

const allSizes = sizes.map(size => {
  return size > 38 ? (size + 1) : size;
});
4
captain_k_nuckles•

bonus, if it's a single line you can omit the return and {}

const allSizes = sizes.map(size => size > 38 ? (size + 1) : size);

2
Fankadore•

You have size => (), instead of size => {}. The closing line should look like });

2