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.
This is also an option:
dosomething()
will only be called ifx==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:
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)
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.:
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 you're not doing the else, why not do:
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:
or, in your case,
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).A tiny addition to this very, very old thread..
Let's say your'e inside a
for
loop and need to evaluate a variable for atruthy/falsy
value with a ternary operator, while in case it'sfalsy
you want tocontinue
- you gonna have a problem because your'e not returning an expression ,you return instead a statement without any value.This will produce
Uncaught SyntaxError: Unexpected token continue
So, if you do want to return a statement and still use one line for your code, while it may seem kinda weird at first glance and may not follow strict language usage, you can do this instead: