Ternary operator with return statements JavaScript

81,119

Solution 1

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

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

Solution 2

why not just this?

 return sort.attr('selected');

Solution 3

From the docs:

Syntax
condition ? expr1 : expr2
Parameters
condition (or conditions) An expression that evaluates to true or false.
expr1, expr2
Expressions with values of any type.

You should pay attention to the Expressions with values of any type., the return xxx is not an expression.

From wikipedia:

An expression is a syntactic construct, it must be well-formed: the allowed operators must have the correct number of inputs in the correct places, the characters that make up these inputs must be valid, have a clear order of operations, etc. Strings of symbols that violate the rules of syntax are not well-formed and are not valid mathematical expressions.

So, in your case you can use:

return sort.attr('selected') ? true : false

Solution 4

Just a comment on your code:

> sort.attr('selected')

seems to be using the jQuery attr method, which used to try and second guess what you wanted and return either the attribute or the property. I think in recent versions it returns the attribute always.

Anyway, the presence of the selected attribute only means that the item (an option element?) is the default selected option, it doesn't mean that it is the currently selected option. For that you need the selected property (jQuery prop method). And since the selected property is a boolean:

> sort.attr('selected') ? true : return false;

can simply be:

 sort.prop('selected');

or without jQuery:

 optionElement.selected;
Share:
81,119
JDillon522
Author by

JDillon522

I love learning the science behind the magic.

Updated on July 08, 2022

Comments

  • JDillon522
    JDillon522 almost 2 years

    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?