6

I've looked at somewhat similar questions like this or this but they are answering a different question as they look at assignment operations. For example my code is

!item.completed ? addTask(item) : null

as I would like to execute a certain function if condition is met or do nothing if it's not met. My question is what would be considered a good practice to pass as an 'empty' 2nd expression?

I saw a lot of people using null, on the other hand I think that using an empty string '' is also a valid option as since there is no assignment happening an empty string is faster to type and doesn't seem to have any cons.

Community
  • 1
  • 1
Anton Kastritskiy
  • 1,248
  • 1
  • 11
  • 23

3 Answers3

16

You could use logical or ||

item.completed || addTask(item) 
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

I think this is not a good use of the ternary operator.

I'd either do:

if (!item.completed) addTask(item);

Or

!item.completed && addTask(item);
plalx
  • 42,889
  • 6
  • 74
  • 90
1

You could use:

!item.completed && addTask(item);

There's no point using a ternary if you don't need it.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
TigOldBitties
  • 1,331
  • 9
  • 15