If/else why should else return true and if false


#1

Continuing the discussion from If / else:

Why is it that if a number modulus 2 has a remainder 0, else would continue to run?
At the moment it makes more sense that if the num % 2 == 0 then else would not run.
Can someone please explain this ? Thanks!!


#2

Ok, so if the first return is not set to return false the loop will continue to run.
If we make the first return, return false then we can move to the else statement and say else return true, to end the loop.


#3

He's basically stating that if you don't do
if (number % 2 === 0), you're going to also proc else as (Taking the code from the conversation you linked):

var isEven = function(number) {
    if (number % 2) { //incomplete comparison (will produce false) and basically skips this condition to the next one
        return "true";
    } else {
        return "false"; //procs else and since this is true then the function will return "false"
    }
};

The if and else statements are conditionals, meaning if the condition written is true, then the function will output whatever is written between the curly brackets.

There is no loop involved as you only run the if/else once.


#4

Also, true and false should be boolean values, not strings


#5

Oops, forgot about that. Silly me.


#6

it actually make sense. 0 is considered false, and 1 is considered true. So if you have this:

if(num %2)

for even numbers the remainder is zero, which is considered false, so the else clause will run, if you put return true, true is returned for even numbers

for odd numbers the remainder is 1, which is considered true, so the if clause runs, so if you put return false in the if clause, false is returned for odd numbers


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.