Interviewer: Write a function to print true if number is even, and false if odd.
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?
For further actions, you may consider blocking this person and/or reporting abuse
Kaja Uvais -
James Garbutt -
AbuBakar Shabbir -
Parth Dadhaniya -
Top comments (7)
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
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:
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" 😅
I have two solutions:
In this case, you should use switch case because they are faster in comparison of if-else statement and more cleaner syntax.
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;
}
}
?>
function even(int number) {
echo (number % 2 == 0) ? "true" : "false";
}
I hope he didn't go too far in the numbers 😂
Not completed
Why, how come?