lochnesscookie
lochnesscookie

Reputation: 197

Is it okay to use numbers as booleans instead of comparing them to zero?

I have a situation that essentially boils down to the following:

// x is a non-negative integer
if (x > 0){
    doSomething();
}

Of course, the conditional statement could be changed from if (x > 0) to if (x). Is this common practice?

As someone who hasn't worked with javascript before, I'm inclined to just use comparisons so that it's less ambiguous for me. But if most people do take advantage of truthy/falsy values I might as well omit direct comparisons and just get used to it.

Upvotes: 2

Views: 75

Answers (2)

Albizia
Albizia

Reputation: 599

In this context, with x being an integer,

using if(x) makes more sense to check whether x is undefined. For example if x is the parameter of a function, and you want to know that it was correctly given as an input.

On the other hand, If you know that x has a value, writing the comparison if(x>0) explicitly will make more sense, and your code more readable.

Upvotes: 1

mwilson
mwilson

Reputation: 12900

Opinion: If you're handling things like they are true/false values, make them true/false values. Keeping them as numbers will always require all kinds of checks because of type coercion. Not to mention, confusion every time you have to revisit it or developers come on board.

It really depends on what you're using it for, but type coercion is something to always keep in mind with JavaScript as you run into regularly. If you're wanting to play with a true/false value, I would just build logic to evaluate x and figure out if you want it to be true/false.

const x = 0;
const isZero = x > 0;

console.log(isZero);

Generally speaking, it looks like you're after a true/false outcome so I would suggest converting that to a true/false value.

Upvotes: 3

Related Questions