ChatGPT解决这个技术问题 Extra ChatGPT

JavaScript single line 'if' statement - best syntax, this alternative? [closed]

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"): "";
Would be nice if JavaScript supported end of phrase conditionals: document.write("My evil twin emerges") if lemons
I think you might be thinking about the short if, else statement. (variable = (condition) ? true-value : false-value;.) Good luck.

r
revelt

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.


you should know what you are expecting, since empty string and 0 are falsy values, it will fail the execute the second statement
Of course, you can just as well put a more explicit boolean statement in there
@acjohnson55 What do you mean?
I meant that in response to Orlando. Should have used my @ sign. Basically just saying that your approach is still valid if you don't want to rely on truthyness/falseyness
@PeterOlson why are the maintainability objections moot? What if any other developer happens to not use your IDE with its configuration.
w
whirish

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")
P
Peter Mortensen

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");

You don't need brackets on the lemon.
Can be best practice to include () around a conditional statement - removes any confusion as to order of operations etc. for other developers. I typically err towards specifying it except when there's no way for someone decently qualified to get confused.
document.write(lemon ? "foo gave me a bar" : "if condition is FALSE"); :)
I like the brackets as to me they imply a boolean coercion.
M
Marc

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'


In single line short-circuits, we can omit 'return' and it should work as expected. ``` lemons && "foo gave me a bar"; // works! ```
@siwalikm could you explain? This is for the case where you don't want to return lemons (if it's falsey) -- you only want to return "foo gave me bar" when lemons is truthy.
if (lemons) return "foo gave me a bar"; this is wrong. It will give you "Uncaught SyntaxError: Illegal return statement"
@Fenec would you share the browser and version that causes you this error? This worked for me almost 2 years ago and continues to work for me.
C
Community

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
why not use just alert(lemons ? "please give me a lemonade": "then give me a beer");
s
shakee93

This one line is much cleaner.

if(dog) alert('bark bark');

I prefer this. hope it helps someone


K
Kemacal

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


u
user3413838

// Another simple example

 var a = 11;
 a == 10 ? alert("true") : alert("false");

why not simply.. var a = 11; alert(a === 10); ?
@ManuKaracho I see this problem a lot when working with ternary statements. I understand OP may have just been trying to write a simple one but it is rampant in the code I read at work.
alert(a === 10 ? "true" : "false")
@JoshWood the alert will print booleans too, so you can just do alert(a===10) like Manu said.
A
Anita Graham

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".


A
Abdulmajeed
(i === 0 ? "true" : "false")

s
sergiol

It can also be done using a single line when using if blocks like this:

if (blah)
    doThis();

It also works with while loops.


This will fail linting and is not recommended
The OP also asked for a one-liner.
b
brunettdan

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.


S
Sajith Mantharath
**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, '@&'));

"Even assign operation also we can do with round brackets". This is very interesting, I didn't know that it was possible to do assign operations inside these single-line operations.