Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript shorthand if-else and returning

Tags:

javascript

Can the javascript shorthand for if-else return out of a function? If so how would this work.

eg. I have this:

if(boolean){
 return;
}

and I would like to write it as this:

(value)? return;

Chrome complains that return is unexpected. Is there anyway to write something like this so that it is valid?

like image 390
ntkachov Avatar asked Jan 29 '12 19:01

ntkachov


People also ask

How do you shorten if else statements?

The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .

Can you return in an if statement JavaScript?

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number. If the value is omitted, undefined is returned instead.

Can you have 3 conditions in an if statement JavaScript?

Using either “&&” or “||” i.e. logical AND or logical OR operator or combination of can achieve 3 conditions in if statement JavaScript.

What is if/then else JavaScript?

The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.


3 Answers

No, you can't do that unless you return a value. For example if your function had to return a value you could have written:

return boolean ? 'foo' : 'bar'; 

But you cannot stop the execution of the function by returning void using the conditional operator.

like image 51
Darin Dimitrov Avatar answered Sep 20 '22 16:09

Darin Dimitrov


If you intend to return from the function at this point in its execution regardless of whether the test evaluates true or false, you can use,

return (value) ? 1 : 2; 

But if you merely wish to return early when a test evaluates true (for instance, as a sanity-check to prevent execution when parameters are invalid), the shortest you can make it is:

if (boolean) return; 
like image 39
Shiplu Mokaddim Avatar answered Sep 20 '22 16:09

Shiplu Mokaddim


if(boolean) return;

Single line , readable , perfectly valid;

like image 34
sapy Avatar answered Sep 20 '22 16:09

sapy