patman20
patman20

Reputation: 19

Function that takes a number as an argument and returns a boolean javascript

I am new to coding and I have this exercise where I have to write a function that takes a number as argument and returns a boolean. This is the code I wrote but is not working and I am getting the warning

"The function should only have a return statement in its body. You can evaluate a boolean expression an return immediately its value"

var even = function(x) {
  if ((x % 2) === 0) {
    return true;
  } else
    return false;
};

Upvotes: 0

Views: 3846

Answers (3)

Goutham JM
Goutham JM

Reputation: 1

var even = function(x) {
    if (typeof x === "number") {
        if (x % 2 === 0) {
            return true
        } else {
            return false
        }
    } else {
        return false

    }
}

This covers all the edge cases

Upvotes: 0

Owais Ahmed Khan
Owais Ahmed Khan

Reputation: 268

you can just write your function like this

var even = function(x)
{
   return x % 2 === 0
}
 

Upvotes: 0

trincot
trincot

Reputation: 350270

The response you get from the code submission has an important point:

The expression (x%2)===0 is already a boolean, so you can return that expression:

return x%2 === 0;

In general you should avoid this pattern:

if (some_boolean_expression) {
    return true;
} else {
    return false;
}

... since the boolean you return is exactly the same as the boolean expression that is evaluated in the if condition. So it should be just:

return some_boolean_expression;

Upvotes: 2

Related Questions