Reputation: 3674
Can I write the if else
shorthand without the else
?
var x=1;
x==2 ? dosomething() : doNothingButContinueCode();
I've noticed putting null
for the else works (but I have no idea why or if that's a good idea).
Edit: Some of you seem bemused why I'd bother trying this. Rest assured it's purely out of curiosity. I like messing around with JavaScript.
Upvotes: 309
Views: 678970
Reputation: 92367
Probably shortest (based on OR operator and its precedence)
x-2||dosomething()
let x=1, y=2;
let dosomething = console.log;
x-2||dosomething('x do something');
y-2||dosomething('y do something');
Upvotes: 3
Reputation: 2932
A small addition to this old thread..
If you're evaluating an expression inside a for
/while
loop with a ternary operator and want to continue
or break
as a result - you're going to have a problem because both continue
& break
aren't expressions; they're statements without any value.
This will produce Uncaught SyntaxError: Unexpected token continue
for (const item of myArray) {
item.value ? break : continue;
}
If you really want a one-liner that returns a statement, you can use this instead:
for (const item of myArray) {
if (item.value) break; else continue;
}
Upvotes: 7
Reputation: 11754
This is also an option:
x==2 && dosomething();
dosomething()
will only be called if x==2
is evaluated to true. This is called Short-circuiting.
It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:
if(x==2) dosomething();
You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)
Upvotes: 296
Reputation: 33197
What you have is a fairly unusual use of the ternary operator. Usually it is used as an expression, not a statement, inside of some other operation, e.g.:
var y = (x == 2 ? "yes" : "no");
So, for readability (because what you are doing is unusual), and because it avoids the "else" that you don't want, I would suggest:
if (x==2) doSomething();
Upvotes: 754
Reputation: 56809
Technically, putting null or 0, or just some random value there works (since you are not using the return value). However, why are you using this construct instead of the if
construct? It is less obvious what you are trying to do when you write code this way, as you may confuse people with the no-op (null in your case).
Upvotes: 4
Reputation: 234795
Using null
is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.
As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:
if (x==2) doSomething;
else doSomethingElse
or, in your case,
if (x==2) doSomething;
Upvotes: 17
Reputation: 7412
If you're not doing the else, why not do:
if (x==2) doSomething();
Upvotes: 23