Search code examples
javascriptjqueryternary

Ternary operator with return statements JavaScript


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?


Solution

  • You cannot assign a return statement to a variable. If you want active to be assigned the value true or false, just delete the returns:

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

    or maybe better:

    var active = sort.prop('selected');
    

    since .prop always returns true or false, regardless of the initial tag attribute.