Ryan Aulia

Even or Odd

# Problem Solving
Problem
Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.
 
Solution
JavaScript Function to Check Even or Odd:
Explanation:
We define a function called even_or_odd that takes a single parameter called number, which represents the integer we want to check.
Inside the function, we use the modulus operator % to check if the number is even or odd. The modulus operator returns the remainder of a division operation. If a number is even, it will be perfectly divisible by 2, so its remainder when divided by 2 will be 0. If it's odd, the remainder will be 1.
We check if number % 2 === 0. If the condition is true (the number is even), we execute the code inside the if block, which returns the string "Even".
If the condition in Step 3 is false (the number is odd), we execute the code inside the else block, which returns the string "Odd".
Examples:
Let's call the function with some examples to see how it works:
In the first example, we pass the number 5 to the function, and it returns "Odd" because 5 is an odd number.
In the second example, we pass the number 10, which is even, so the function returns "Even".
In the third example, we pass 0, which is also an even number, so the function returns "Even".
In the last example, we pass -3, which is an odd number, and the function returns "Odd". The function works correctly for negative integers as well.
Hope this helps!
JavaScript Playground
JavaScript
Loading...
Console