Search code examples
jqueryif-statementcheckboxexpressionwarnings

jQuery: Expected an assignment or function call an instead saw an expression for an ifelse shortstatement?


In my Komodo IDE i get a warning message

"Expected an assignment or function call an instead saw an expression"

for this line:

data.aktiv == '1' ? $('#aktiv').attr('checked', 'checked') : $('#aktiv').attr('checked', false);

and for this line

 $('#aktiv').isCheck() ?  aktiv = 1 : aktiv = 0;

What is here the problem?


Solution

  • It's warning you that you're abusing the conditional operator as a replacement for if/else. To use the conditional operator properly, change it to:

    $('#aktiv').attr('checked', data.aktiv == '1' ? 'checked' : false);
    

    and

    aktiv = $('#aktiv').isCheck() ? 1 : 0;
    

    For the general case, if you can't use a shortcut like the above, and you have code like

    condition ? statement1 : statement2
    

    you can fix the linting error by using

    if (condition) {
      // statement1
    } else {
      // statement2
    }