2

i want to check if a number is even by use of function and return in Javascript. here goes my code. It should return true when number is even otherwise it should return false.

var isEven = function(number) {
    if(number%2 === 0) {
        return "true";
    } else {
        return "false";
    }
};

the code doesn't work. Instead it works when the quotation marks ( "...") around true and false are removed. Why? I mean the words true and false are strings, hence should be included inside quotation marks. please help,

2
  • true and false are booleans, not strings. Commented Jun 25, 2016 at 10:55
  • 1
    The simplest way is just function isEven (num) { return num % 2 === 0 }. Commented Jun 25, 2016 at 10:56

4 Answers 4

4

If you put true and false in quotation marks, it will return a string value, because "true" is a string, whereas true is not. If you want to return a boolean, just return true or false.

if(number % 2 === 0) return true;
else return false;
Sign up to request clarification or add additional context in comments.

Comments

4

it should works:

var isEven = function(number) {
    return !Boolean(number % 2);
};

in additional how to create isOdd:

var isOdd = function(number) {
    return !isEven(number);
};

Reason why you can't return "true" for boolean:

Everything that exists between marks "..." in javascript's recognized as type string. This also applies to empty string "", some examples:

typeof("") => "string"
typeof("true") => "string"
typeof(true) => "boolean"

Comparison with others languages you have to pay attention for size of characters, fe:

typeof(TRUE) => "undefined" (because it could be name of variable)

In additional: be consider to use == and ===. Example:

"" == 0 => it's a true
"" === 0 => it's a false

Some examples for build-in Boolean function:

Boolean("") => false
Boolean("1") => true
Boolean("0") => true

1 Comment

The use of Boolean is not necessary here. Just use return !(number % 2);.
0

You may try doing like this

var isEven = n => !(n%2);
console.log(isEven(1));
console.log(isEven(2));

Comments

0

You don't need the if at all. Just return the result of the comparison

var isEven = function(number) {
   return number%2 === 0;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.