true : false
I try not to be too pedantic about grammar, but I have a few pet peeves. It bothers me when people use less instead of fewer, and don't get me started on the overuse of literally.
In JavaScript, it feels like nails on a chalkboard whenever I see a conditional which redundantly evaluates to true
or false
. Take this example:
var isEmpty = function (array) {
if (array.length === 0) {
return true;
} else {
return false;
}
};
Because isEmpty
should return true
or false
, the developer did exactly that. However, he failed to realize that the condition itself is already a boolean. The same function could be rewritten as:
var isEmpty = function (array) {
return array.length === 0;
};
Here's an example where the condition is not already a boolean:
var docExists = function (id) {
if (Collection.findOne(id)) {
return true;
} else {
return false;
}
};
In this situation we should use a !! to coerce the result of findOne
:
var docExists = function (id) {
return !!Collection.findOne(id);
};
And that's it! Now go write fewer lines of code.