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?
You cannot assign a return statement to a variable.
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.
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.
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.
You can return from a ternary operator in javascript like this:
return sort.attr('selected') ? true : false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With