Using Return in Ternary Operator

Why can't we have return in the ternary operator?

The ternary operator evaluates to an expression and expressions can't contain a return statement (how would that behave if you were to assign the expression to a variable?). However, you could very well return the result of a ternary operator, i.e. return condition? returnValue1 : returnValue2;

On your specific point, I don't see why you would like to return. It looks like you're trying to do something only if a condition is fulfilled. A simple if statement would probably be more adequate there.

C – How to use an exit/return statement in ternary operator?

How to use an exit/return statement in ternary operator?

You cannot. The second and third operands of a ternary operator must be expressions, and a return statement is not an expression (see Ternary operators and Return in C). It is, however, allowed for the two to both be void expressions, such as exit(1), in which case the result of the operation is also a void expression.

Additionally, with respect to your specific code, the comma operator (,) has the lowest precedence of all C operators. Therefore, if you intend to use a comma expression as an operand in any other operation, then you need to parenthesize it.

I wanted to formulate these two if statements in a shorter way:

Why? Mere conciseness or brevity is not a useful objective. If it makes your code hard for a human to read and understand, then making your code shorter is a liability.

But if you mean that you want to express the same thing more simply, more clearly, and / or less redundantly, then that can lead you toward forms that also happen to be shorter. For example, you can encapsulate the logic in a function or macro. Personally I often supply a macro that looks something like this:

#define ERROR_IF_NZ(cond, message) do { \
if (cond) { \
fputs(message, stderr); \
exit(1); \
} \
} while (0)

Using that, your code could look like this:

ERROR_IF_NZ(argc != 2, "Error X\n");
ERROR_IF_NZ(NULL == file, "Cannot open file!\n");

Adjust the macro name so that it makes the most sense to you, and look! It is not only clearer than the original code, but shorter, too, even if you count the length of the macro definition.

Update

Edits to the question have pretty much mooted this answer. If you already have functions that serve the the same role that a macro such as described here would do, then just call them. There is no redeeming value in replacing the functions and the calls to them with a ternary expression, nor is it worth any effort to convert the functions you have into macros. Certainly, reducing source code size is not an reasonable motivation for such changes.

UnexpectedToken error when I try to use return with ternary operator but not with if statement?

Why does this happen?

Because return is a statement, and you can't put statements where only expressions are allowed.¹ The conditional operator's operands must be expressions, not statements. (You'd have the same problem with throw, just FWIW, though there's talk of adding a throw operator... Or with while or for or any other statement.)

The if is probably your best bet.

If you were really, really intent on just using a single expression, you could put the return at the start so the single expression is what follows it:

function monthName(nr) {
return 0 < nr < 13 ? alert("Month: " + months[nr]) : false;
}

Note that that relies on the fact that alert returns undefined in order to maintain the two return values you were providing in your if example (undefined if the alert was shown, false if not). Interestingly, the spec doesn't explicitly say that alert returns undefined but I think we can safely accept that it's implicitly specified (not least because the implicit return of any non-arrow JavaScript function is undefined unless return <value> is used).


¹ (You can do the opposite; JavaScript has the concept of the "expression statement" which means any expression is also a valid statement.)

Return statement inside JavaScript ternary operator expression

No its not possible. The operands of the ternary operator are expressions. And return is a statement. You should use if else. According to MDN

Parameters


condition
An expression whose value is used as a condition.

exprT, exprF
Expressions with values of any type.

Ternary operator with return statements JavaScript

You cannot assign a return statement to a variable. If you want active to be assigned the value true or false, just delete the returns:

var active = sort.attr('selected') ? true : false;

or maybe better:

var active = sort.prop('selected');

since .prop always returns true or false, regardless of the initial tag attribute.

How do I return true or false for ternary operator in Javascript?

What you tried:

sum % 10 === 0 ? return true : return false; 

This does not work, because return is a statement and not an expression. A statement can not be used inside of an expression.

sum % 10 === 0 ? true : false; 

This works, but without a return statement, it is just an expression without using it.

Finally, you need to retur the result of the conditional (ternary) operator ?:, like

return sum % 10 === 0 ? true : false; 

For a shorter approach you could return the result of the comparison without ternary.

return sum % 10 === 0;

return with Ternary and warlus operators

The comments suggest that you can't use the walrus operator in a return statement, that's incorrect - you just have a syntax error.

This works, but is pointless, as also pointed out in the comments:

from typing import List, Optional

def get_index(elements: List[int], i: int, boundary: int) -> Optional[int]:
return (x := elements[i] if elements[i] > boundary else None)

print(get_index([1, 2, 3], 2, 1))

All you need is parentheses around the walrus assignment and the value of the expression will be the assigned value.

But why assign to x if all you do is return that value. Instead:

from typing import List, Optional

def get_index(elements: List[int], i: int, boundary: int) -> Optional[int]:
return elements[i] if elements[i] > boundary else None

print(get_index([1, 2, 3], 2, 1))


Related Topics



Leave a reply



Submit