user1031143
user1031143

Reputation: 828

Return 0 as integer not bool

I have a function where if successful, it returns an integer, but if not it just returns false.

Here's part of my code:

    function hellofunc(x) {
//....

        if (returnvalue.length == 1) {
            return returnvalue[0];
        } else if (returnvalue.length > 1) {
            return returnvalue[rx(0, returnvalue.length - 1)];
        } else {
            return false;
        }
    }

When the function calls this -> return returnvalue[0]; it gives 0 as an integer.

But when I call hellofunc(something); I see it writes to console "0" but when I type something false it returns false,

JavaScript thinks 0 is false? So what do I do here? Do I do this?

hellofunc(something)!==false

Or is there any better solution?

Upvotes: 0

Views: 213

Answers (2)

Bartlomiej Lewandowski
Bartlomiej Lewandowski

Reputation: 11180

In most programming languages 0 is false. It comes from the representation of a number in binary. Since in the boolean logic you only have 2 choices - True and False, you only need one bit to represent that. 1 for True and 0 for False.

Upvotes: 1

Rajat Singhal
Rajat Singhal

Reputation: 11264

hellofunc(something) !== false

as you said..no better solution..:)

Upvotes: 3

Related Questions