Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  97] [ 4]  / answers: 1 / hits: 9621  / 9 Years ago, wed, may 20, 2015, 12:00:00

How to use return in ternary operator in jQuery?



myfunc: function() {
for(i = 0; i < 10; i++) {
(6 == i) ? Do_This_and_This : return true;
}
//Error: Expected an operand: but found return false or true.
}


As per understanding return false will return back to function and breaks the loop and return true will work as continue which moves to next iteration.



Please validate understanding and provide solution for same. If there is another way to do it please suggest



UPDATE: My solution have big javascript and i have put small snippet for an instance that what it is doing.
Like in for there are nested ifs` and nested ternary operators too. Lets give more snippet



myfunc: function() {
for(i = 0; i < 10; i++) {
($.inArray(questionNumber, questions) > -1) ? ((Ra === ) ? Report= Report+<tr><td>lakslak</td></tr> : Report= Report+<tr><td>lasaaakslak</td></tr>) : return false;
}
}

More From » jquery

 Answers
5

The ternary operator is used on expressions, not on statements. You cannot put a return inside there - if you need to, use an if statement.



However, in your case can easily move the return outside:



return (6 == i) ? false : true;


Although you'd better do



return 6 != i;





For your updated code, I'd suggest to use



myfunc: function(){
for (var i=0; i<10; i++) {
if ($.inArray(questionNumber, questions) > -1)
Report += (Ra===) ? <tr><td>lakslak</td></tr> : <tr><td>lasaaakslak</td></tr>;
// or even
// += <tr><td>+(Ra===?lakslak:lasaaakslak)+</td></tr>;
else
return false;
}
}


You cannot use a conditional operator to return in one case but not the other, because return is a statement, and the conditional operator's operands are expressions, not statements. In JavaScript, you can use an expression where a statement is expected (it becomes an ExpressionStatement), but not vice-versa.


[#37010] Tuesday, May 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adrienkeithr

Total Points: 503
Total Questions: 126
Total Answers: 110

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;