JavaScript #188690
Replies: 2 comments
-
|
Hello! This is a great puzzle to understand how map works under the hood in JavaScript. Here are the answers to your questions:
JavaScript In your code, the if (num % 2 === 0) condition only returns a value for even numbers. When the iteration hits an odd number (like 1 and 3), the condition is not met, and the function reaches the end without a return statement. In JavaScript, when a function doesn't explicitly return anything, it returns undefined by default.
Solution A: If you want to keep the original odd numbers ([1, 4, 3, 8]) JavaScript // A cleaner way using the ternary operator: JavaScript Happy coding! 🚀 |
Beta Was this translation helpful? Give feedback.
-
|
[undefined, 4, undefined, 8]Why:
Fix (keep odd numbers, double evens): let arr = [1, 2, 3, 4];
let result = arr.map(num => (num % 2 === 0 ? num * 2 : num));
console.log(result); // [1, 4, 3, 8]If you wanted only doubled evens ( |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Body
Body (Text):
“Hello developers! 👋
Today I’m playing around with JS arrays and ran into a small puzzle.
Question:
What do you think
console.log(result)will output?Why does it behave that way?
How can we fix it so the result becomes something closer to
[1, 2, 3, 4]?That’s what makes JavaScript interesting — small code, big puzzles! 🧩
Guidelines
Beta Was this translation helpful? Give feedback.
All reactions