Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator with return statements JavaScript [duplicate]

I need to return true or false if an option in a drop down selected.

This is my code:

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

I get an error that the first return is unexpected.

Why?

like image 758
JDillon522 Avatar asked Oct 17 '13 23:10

JDillon522


People also ask

Can you put a return in a ternary operator JavaScript?

You cannot assign a return statement to a variable.

Can you use return with ternary operator?

The ternary operator is used to return a value based on the result of a binary condition. It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a function.

Can ternary operator have two conditions?

In the above syntax, we have tested 2 conditions in a single statement using the ternary operator. In the syntax, if condition1 is incorrect then Expression3 will be executed else if condition1 is correct then the output depends on the condition2. If condition2 is correct, then the output is Expression1.

How do you use ternary operator for 3 conditions?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


1 Answers

You can return from a ternary operator in javascript like this:

return sort.attr('selected') ? true : false; 
like image 171
George K Avatar answered Sep 19 '22 20:09

George K