 # Please explain how it work

Please explain how this function works. Thak you.

Correct me if i’m wrong, but this function shouldn’t work you are just comparing the values. If you intend checking for even numbers, here is the code

Even Numbers

``````function isEven(n) {
return n % 2 == 0;
}
``````

Your function is missing the modulus operator : %

What it does is it will return true for all even numbers(both positive and negative).
[Even numbers are those numbers which when divided by 2,gives remainder as 0]

isEven(num)

when this function is called it first checks if it is 0, it will return true.
If it is not zero it will check if it is 1, if that’s the case, then number is not even,it is odd.
if the number is negative ,it will change it to positive as putting a negative sign before a negative number makes it positive.
If all these cases don’t match,then number gets decreased by 2 and the function is called again by the decreased number,until it return either 0 or 1 where the program ends.
Hope it helps!

Yes, thanks. Maybe it is too hard for me yet .

This function works, but it won’t have the best performance using recursion. Basically what the function is doing is taking the value and subtracting 2 from it until it gets a result of either 0 or 1. If the number passed in is negative then the (-n) converts it to positive. Since recursion just keeps adding things to the memory stack, it’s possible that with a large enough number, the client could run out of memory and break before it returns the result. @FrankDupree’s response is a much cleaner and less error prone solution. If you want to keep similar logic, but remove the recursion, you could use a while loop.

``````function isEven(n){
// converts value to positive
if (n < 0)
n = -n;

// only enters loop if value is greater than 1
// then subtracts 2 from value until it is less than or equal to 1
while (n > 1){
n = n - 2;
// can also be written n -= 2
}

// if value is 0 then number is even
// otherwise it is odd
return n === 0;
}
``````

That’s looks greater than my 