0

So I was studying jQuery and at some point I encounter this code at one of the examples of some random sites.

$("#schedchkall").prop('checked', ($('.betchkbox:checked').length == $('.betchkbox').length) ? true : false);

Now my question is what is the meaning of ? true : false ? What's the use of it?

  • It's the ternary operator, think about it as a short if...then--else https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Conditional_Operator – chepe263 Jun 13 '15 at 01:13
  • 4
    Using the conditional operator like this is an anti-pattern. The whole `(...) : true : false` expression can be replaced by the `...` part. – Felix Kling Jun 13 '15 at 01:13
  • ow! now I know. Thank you experts! –  Jun 13 '15 at 01:23
  • A single DOM selection would be better than two overlapping selections. `$(".betchkbox:not(:checked)").length === 0` –  Jun 13 '15 at 02:00

2 Answers2

1

That is the Conditional ternary operator

It's a simplified if statement.

You could "translate" that line into this

var condition;
if($('.betchkbox:checked').length == $('.betchkbox').length) {
    condition = true; // -> ?
} else {
    condition = false; // -> :
}
$("#schedchkall").prop('checked', condition);
Eric Martinez
  • 31,277
  • 9
  • 92
  • 91
  • 2
    or just `$("#schedchkall").prop('checked', $('.betchkbox:checked').length == $('.betchkbox').length);` – mmgross Jun 13 '15 at 01:16
0

It means if $('.betchkbox:checked').length == $('.betchkbox').length) is true, it will return true such that it becomes $("#schedchkall").prop('checked', true);

If it is false, it becomes $("#schedchkall").prop('checked', false);

chris97ong
  • 6,870
  • 7
  • 32
  • 52