Closed. This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing this post. Closed 2 years ago. Improve this question
It's been clearly put, although opinion none the less, that forgoing curly brackets on a single line if
statement is not ideal for maintainability and readability.
But what about this?
if (lemons) { document.write("foo gave me a bar"); }
It's even more compressed, and if expanded, the curly brackets won't be forgotten. Are there any blatant problems, and if not, what are the considerations? I feel like it's still very readable, at least as much as a ternary operator anyway. It seems to me like ternary operators aren't suggested as much due to readability, although I feel like that that conclusion isn't quite as unanimous.
The evil twin in me wants to suggest this, although the syntax obviously isn't meant for it, and is probably just a bad idea.
(syntax) ? document.write("My evil twin emerges"): "";
document.write("My evil twin emerges") if lemons
variable = (condition) ? true-value : false-value;
.) Good luck.
I've seen the short-circuiting behaviour of the &&
operator used to achieve this, although people who are not accustomed to this may find it hard to read or even call it an anti-pattern:
lemons && document.write("foo gave me a bar");
Personally, I'll often use single-line if
without brackets, like this:
if (lemons) document.write("foo gave me a bar");
If I need to add more statements in, I'll put the statements on the next line and add brackets. Since my IDE does automatic indentation, the maintainability objections to this practice are moot.
I use it like this:
(lemons) ? alert("please give me a lemonade") : alert("then give me a beer");
alert(lemons?"please give me a lemonade":"then give me a beer")
You could use this format, which is commonly used in PHP:
(lemon) ? document.write("foo gave me a bar") : document.write("if condition is FALSE");
lemon
.
document.write(lemon ? "foo gave me a bar" : "if condition is FALSE");
:)
As has already been stated, you can use:
&& style
lemons && document.write("foo gave me a bar");
or
bracket-less style
if (lemons) document.write("foo gave me a bar");
short-circuit return
If, however, you wish to use the one line if
statement to short-circuit a function though, you'd need to go with the bracket-less version like so:
if (lemons) return "foo gave me a bar";
as
lemons && return "foo gave me a bar"; // does not work!
will give you a SyntaxError: Unexpected keyword 'return'
lemons
(if it's falsey) -- you only want to return "foo gave me bar" when lemons
is truthy.
can use this,
lemons ? alert("please give me a lemonade") : alert("then give me a beer");
explanation: if lemons
is true then alert("please give me a lemonade")
, if not, alert("then give me a beer")
lemons? alert("please give me a fancy beer with a lemon wedge in it"): alert(please give me a beer")
FTFY
alert(lemons ? "please give me a lemonade": "then give me a beer");
This one line is much cleaner.
if(dog) alert('bark bark');
I prefer this. hope it helps someone
As a lot of people have said, if you're looking for an actual 1 line if then:
if (Boolean_expression) do.something();
is preferred. However, if you're looking to do an if/else then ternary is your friend (and also super cool):
(Boolean_expression) ? do.somethingForTrue() : do.somethingForFalse();
ALSO:
var something = (Boolean_expression) ? trueValueHardware : falseATRON;
However, I saw one very cool example. Shouts to @Peter-Oslson for &&
(Boolean_expression) && do.something();
Lastly, it's not an if statement but executing things in a loop with either a map/reduce or Promise.resolve() is fun too. Shouts to @brunettdan
// Another simple example
var a = 11;
a == 10 ? alert("true") : alert("false");
var a = 11; alert(a === 10);
?
alert(a === 10 ? "true" : "false")
alert(a===10)
like Manu said.
I've seen many answers with many votes advocating using the ternary operator. The ternary is great if a) you do have an alternative option and b) you are returning a fairly simple value from a simple condition. But...
The original question didn't have an alternative, and the ternary operator with only a single (real) branch forces you to return a confected answer.
lemons ? "foo gave me a bar" : "who knows what you'll get back"
I think the most common variation is lemons ? 'foo...' : ''
, and, as you'll know from reading the myriad of articles for any language on true, false, truthy, falsey, null, nil, blank, empty (with our without ?) , you are entering a minefield (albeit a well documented minefield.)
As soon as any part of the ternary gets complicated you are better off with a more explicit form of conditional.
A long way to say that I am voting for if (lemons) "foo"
.
(i === 0 ? "true" : "false")
It can also be done using a single line when using if
blocks like this:
if (blah)
doThis();
It also works with while
loops.
Example in arrow functions:
let somethingTrue = true
[1,2,3,4,5].map(i=>somethingTrue && i*2)
In promises:
Promise.resolve()
.then(_=>checkTrueFalse && asyncFunc())
.then(_=>{ .. })
Otherwise:
if(somethingTrue) thenDo()
If it's just a simple conditional, I prefer using if(value) whenever possible because the word if in the beginning of the statement says more about what's happening than paranthesis and questionmarks.
**Old Method:**
if(x){
add(x);
}
New Method:
x && add(x);
Even assign operation also we can do with round brackets
exp.includes('regexp_replace') && (exp = exp.replace(/,/g, '@&'));
Success story sharing