Simplify ternary operator

1k Views Asked by At

I want to set the variable notEmpty to true or false with a ternary operator, but my VSCode sonarlint marks it underlined in blue with the comment: Simplify this expression

Code: const notEmpty = list.length > 0 ? true : false;

This actually works, but could be better.

2

There are 2 best solutions below

2
On

try this:

const notEmpty = list.length ? true : false;

no need to compare it to 0 as it returns 0 when it's empty which is false, otherwise it's true

0
On

You can also do this:

const notEmpty = Boolean(list.length);

Converting the value of 0 to false, or 1 to true

As mentioned in the comments above this is equivalent to:

const notEmpty = !!list.length;