Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Say I've a simple form and I want to check whether form has changed or not. If its changed submit it else prevent form submission, so I used return and instead of using if-else statement I tried to use ternary operation but unfortunately I was hit with error Uncaught SyntaxError: Unexpected token return but I did not understand why this error? Is ternary operation only used to assign? Not sure on this part. Below is just a sample of what I was trying to do.

var form_original_data = $("#frmProfile").serialize();    $("#frmProfile").on('submit', function(e) {    e.preventDefault();    $("#frmProfile").serialize() != form_original_data ? $("body").append('changed') : return;  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <form id="frmProfile">    <input type="text" value="name" />    <input type="submit" value="Go" />  </form>
like image 368
Guruprasad J Rao Avatar asked Feb 05 '16 19:02

Guruprasad J Rao


People also ask

Can I use return in a ternary operator?

The ternary operator consists of a condition that evaluates to either true or false , plus a value that is returned if the condition is true and another value that is returned if the condition is false .

What is the return type of ternary operator?

The return type of ternary expression is bounded to type (char *), yet the expression returns int, hence the program fails. Literally, the program tries to print string at 0th address at runtime.

Can we write return in conditional operator?

[D]. Explanation: In a ternary operator, we cannot use the return statement.

Why we should not use ternary operator?

They simply are. They very easily allow for very sloppy and difficult to maintain code. Very sloppy and difficult to maintain code is bad. Therefore a lot of people improperly assume (since it's all they've ever seen come from them) that ternary operators are bad.


1 Answers

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.

like image 81
Aaron Avatar answered Oct 05 '22 23:10

Aaron