Posted on

# Can you simplify this code for the guy?

Interviewer: Write a function to print true if number is even, and false if odd.

Can you simplify this code for the guy?

## Top comments (8)

JoelBonetR ðŸ¥‡ • Edited

For a given array of numbers:

numbers.forEach( function (let el) {
(el%2 === 0) ? console.log('true') : console.log('false');
});

It's more or less the same than @mranyx did, it's correct. 0 returns even which is correct and floats are not odd nor even (only integers can be).

For that given array:
Â [0, 1, 2, 3, 5.1, 4.3, 4.2]

it returns true, false, true, false, false, false false.

I just coded it and tried it on the browser's console while reading xD

Aleksandr Hovhannisyan • Edited

The ternary is unnecessary. The modulo operator already returns a boolean expression, so it's redundant. It's like saying "true or false ? true: false."

Here's a simplified version:

``````numbers.forEach(num => console.log(num % 2 === 0));
``````

JoelBonetR ðŸ¥‡

totally agree ðŸ˜†
I took the other answer as start point only to figure out why the OP said it's incomplete, so i used a foreach for testing purposes and commented it "as is" ðŸ˜…

Pankaj Sharma

I have two solutions:

1. In this case, you should use switch case because they are faster in comparison of if-else statement and more cleaner syntax.

2. But what if you don't want to write every time if else if try this

<?php
\$compare_length = 20;
\$match = 7;
for (\$i = 1; \$i < \$compare_length) {
if (\$match === \$i) {
echo 'Match Found';
break;
}
}

?>

MrAnyx • Edited

function even(int number) {
echo (number % 2 == 0) ? "true" : "false";
}

I hope he didn't go too far in the numbers ðŸ˜‚