var inventory = [
{ id: 1, name: 'apples', quantity: true },
{ id: 2, name: 'apples', quantity: false },
{ id: 3, name: 'cherries', quantity: true }
];
var result = inventory.find(inv => inv.id === 5) ? true: false;
Sonarqube is suggesting to simplify the expression below -
var result = inventory.find(inv => inv.id === 5) ? true: false;
I have no idea how to simplify it. Can anyone please help to simplify this ? Sonarqube is suggesting that Boolean literals should not be redundant.
Sonarqube makes a remark that returning a direct boolean value based on condition is just obvious. Consider the following:
if (condition) {
return true;
} else {
return false;
}
or equivalent:
return (condition) ? true : false;
condition
itself evaluates to true
or false
, so it's like saying 'if true then true, if false then false'. Therefore it is just enough to return result of the condition itself, like so:
return (condition);
Now your specific example makes implicit coalescing to a boolean value by using find()
return value in a boolean context (implied by ?:
operator). Since find()
returns undefined
when the requested object is not found, your code makes use of falsy value of undefined
to resolve ?:
to true or false branch. It seems like you are interested in checking whether the value is present in the array, meaning whether find()
returns something else than undefined
, meaning:
var result = inventory.find(inv => inv.id === 5) !== undefined;