Difference Between If (x) { Foo(); } And X ? Foo() : 0;
Solution 1:
Snippet #2 is an invalid ECMAScript expression since it lacks the required : blah
in order to make it a ternary.
EDIT: There isn't really a difference between the two snippets, they both invoke foo
if x
is truthy. If x
is falsy (undefined/false/empty string/0/) then first snippet wouldn't evaluate to anything, latter snippet would evaluate to 0
but that 0
really has no impact on the script.
Solution 2:
I think you meant to ask the following
// Why should I use
if (x) {
do();
}
// instead of
x && do();
or
// Why should I use
if (x) {
do();
} else {
dont();
}
//instead of
x ? do() : dont()
As they are written, there is no difference in the output. I don't like using the ternary or the && operator in these cases because of the semantics of using the ternary and &&. A ternary returns a value that you're not using, as does the && expression. Therefore, I'd rather use the way the language intends operators to be used.
However, I love using && for null checks
varval = obj && obj.getValue();
Note that in this case, we are using the return value of the expression
Solution 3:
Generally, if
is a statement (e.g. you can't assign it to a variable) and the ternary operator ?:
is part of an expression (yields a value which can be assigned to variables).
Also, the if
block can contain statements while the components of ?:
can only contain expressions.
In the example you give, there is no difference, since you don't use the result of the ?:
.
Both snippets evaluate foo()
only if x is a true value.
Post a Comment for "Difference Between If (x) { Foo(); } And X ? Foo() : 0;"