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.

4
  • 2
    The ternary operator isn't appropriate here if there is no third thing. Just use an if. Commented Dec 2, 2016 at 20:53
  • 1
    why not just use if? if minification is your goal then '' is better Commented Dec 2, 2016 at 20:53
  • ternary is generally shorter and seems more readable to me Commented Dec 2, 2016 at 20:57
  • I'm voting to close this question as off-topic because it belongs on codereview but I can't transfer there. Commented Dec 3, 2016 at 4:15

3 Answers 3

15

You could use logical or ||

item.completed || addTask(item) 
Sign up to request clarification or add additional context in comments.

1 Comment

Never thought about the OR operator in this way, thank you for opening the new use for it
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);

Comments

1

You could use:

!item.completed && addTask(item);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.