Reputation: 1114
Suppose, an if statement
is like following
if(true) { doSomething() }
and I will write it as
true ? doSomething() : null
The result is same in both but there must be a difference in the purpose of both.
Could someone share their experience about
null
make . Is it a bad practice ?null
rather writing a complete else statement
PS: It does not make a big difference to write an
else case
either. So I hope answers or comments are not related to that.
Upvotes: 0
Views: 2678
Reputation: 140613
Beyond that:
true ? doSomething() : null
will simply surprise most readers; no matter what programming language is used.
In that sense: this is a good example for a "bad" style; that is not helping the readability/clearness of your source code. Surprising your readers (in that sense) isn't a good idea:
Upvotes: 0
Reputation: 30340
if
is a statement, a list of steps without an inherent value.
a ? b : c
is an expression - it evaluates to the value of either b
or c
.
The ternary operator works well where you want to use the result of a conditional:
// After this line, `result` has either the return value of `doSomething` or `null`.
const result = value ? doSomething() : null
if
works well where you don't need to use the result, you want to run several statements in any conditional branch or you want to chain several if/else if/else
conditions.
In most languages You can chain ternary expressions them to mimic if/else if/else
, but that can be quite hard to read.
Upvotes: 3
Reputation: 73568
The ternary operator is not an alternative to if
(in many aspects). Even though you can write all sorts of hacks that imitate other kinds of code, I can't imagine any competent programmer would even think of using ternary here instead of the normal, perfectly readable and working if clause.
It should be noted that the ternary operator isn't a very powerful tool. It can allow you to write some code in a shorter way sometimes, but that's hardly a reason to try to use it everywhere possible.
Upvotes: 1