0

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.

Jon Wood
  • 1,531
  • 14
  • 24

2 Answers2

0

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

Karl L
  • 1,645
  • 1
  • 7
  • 11
  • 2
    this could even be simplified to `!!list.length` if a boolean is actually needed. But by default. `list.length` is a truthy statement already if it's not 0 – A. L May 20 '20 at 01:43
  • I agree with with the double NOT operator "!!". So the first ! coerce the value to a boolean and inverse it, then the second ! reverses it to the original boolean equivalent. – Karl L May 20 '20 at 01:52
0

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;
Jon Wood
  • 1,531
  • 14
  • 24