dsjkncdjksncdskjcn dsjkncdjksncdskjcn - 6 months ago 13
Javascript Question

How to use an arrow function to return an array with all its even elements incremented by 1, and odd elements decremented by 1?


Task

You are given a variable, my_function. Your task is to assign it with
an arrow function. The my_function should take an array as its
parameter and return an array with all its even elements incremented
by 1, and odd elements decremented by 1.

Note


  • DON'T use function instead of an arrow function.

  • DON'T print anything on the console.

  • Replace the blank (_________) with an arrow function.

  • The name of the array parameter can be anything. For example, some_array.




My current code is below, but the Current Buffer told me there is SyntaxError: Unexpected token if.

// write the correct arrow function here
var my_function = some_array => some_array.map((currentValue, index) => if(index % 2 === 0) currentValue + 1; else currentValue - 1;);

Answer

You can use this:

var my_function = some_array => some_array.map(
    (currentValue, index) => currentValue + (currentValue % 2 ? -1 : 1)
);

Note that you had a spelling mistake in currentValue and that you should not use if but the ternary operator.

Also, you can save a comparison with zero (== 0), by swapping the condition and sub-expressions that follow it. And finally, I moved currentValue out of the conditional part, since it has to be used for both cases.

Comments