Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you write an if statement in one-line JavaScript?

Writing a one-line if-else statement in JavaScript is possible by using the ternary operator. Running this code prints “Adult” into the console. This code works fine. But you can make it shorter by using the ternary operator.

What is the correct syntax for an if statement in JavaScript?

In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

What can I use instead of if else in JavaScript?

Javascript offers a ternary operator which acts like a one-line if / else statement with a single condition. It works really well for conditionally assigning a value to a variable.


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

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

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'