Skip to content
Discussion options

You must be logged in to vote

The code outputs [undefined, 4, undefined, 8] because .map() expects a return value for every item. When num is odd (1 and 3), if condition is false, so no return happens — which defaults to undefined in JS arrow functions without explicit return.

That's classic JS quirk: implicit return only if single expression, but with if/else blocks, you need explicit returns everywhere, or it falls through to undefined.

To fix it for something closer to [1, 4, 3, 8] (keep odds same, double evens):

let arr = [1, 2, 3, 4];
let result = arr.map(num => {
  if (num % 2 === 0) {
    return num * 2;
  } else {
    return num;
  }
});
console.log(result);  // [1, 4, 3, 8]

Replies: 9 comments 6 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@Abdumajidov2005
Comment options

Comment options

You must be logged in to vote
1 reply
@Abdumajidov2005
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@Abdumajidov2005
Comment options

Comment options

You must be logged in to vote
2 replies
@Abdumajidov2005
Comment options

@Abdumajidov2005
Comment options

Answer selected by Abdumajidov2005
Comment options

You must be logged in to vote
1 reply
@Abdumajidov2005
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question Ask and answer questions about GitHub features and usage Programming Help Discussions around programming languages, open source and software development
9 participants