-1

I have a function and if statement that I need to print "even" in the console. The statement is literally, "If num is an even number, print out "even". Don't do anything if num is an odd number."

I thought it would work if I put (num) equal to Math.random. But I got undefined. I also tried setting (num) equal to a specific number and I'm still getting undefined in the console.

How do I get this to print "even"?

function isEven(num) {
    let random = Math.random();
    if (num = random ){
        console.log("even");
    }
}
Jasmine
  • 9
  • 2
  • 2
    `=` is assignment, `==` is comparison. But equality is not the same as odd/even. – Dave Newton Oct 13 '22 at 12:32
  • Take a look at the [Remainder operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder) `%`. This should help you further – S-Flavius Oct 13 '22 at 12:34
  • 1
    Even means divisible by 2. Comparing to a random number (which will have an astronomically tiny chance of ever matching anyway) won't do you any good there... – CherryDT Oct 13 '22 at 12:34
  • 1
    Btw the "undefined" is just the return value of your function. You aren't returning anything. – CherryDT Oct 13 '22 at 12:35
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Oct 13 '22 at 12:42

2 Answers2

1

Try something like this:

function isEven(num) {
    if (num % 2 == 0) {
        console.log("even");
    }
}

% gives the remainder of integer division, and so if you do num % 2 and the result is 0 then your number is even! Otherwise, it is an odd!

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Amaroke
  • 61
  • 8
0

I don't understand why you made a random variable to generate random number you try this instead

function isEven(num) {
  if (num % 2 == 0) {
    console.log("even");
  }
}
Dave Newton
  • 158,873
  • 26
  • 254
  • 302