Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I use the following code:

  var newValue = ($(event.target).is(":checked")) ? 1 : 0;
  var oldValue = (!$(event.target).is(":checked")) ? 1 : 0;
  sendMessage(this.name, oldValue, newValue);

Is there any better approach?

share|improve this question

4 Answers 4

up vote 8 down vote accepted

sendMessage(this.name, +!event.target.checked, +event.target.checked)

Not your sending sendMessage(text, !bool, bool) which is silly just send one bool.

Also $(thing).is(":checked") is stupid (jQuery ಠ_ಠ)

share|improve this answer
LA_, note that +true == 1, and +false == 0 in JS. –  Quentin Pradet Mar 3 '12 at 20:47

As Cygal noted in one of the comments, using the unary operator (+) coerces true and false into numbers. So doing +true will yield 1 while using +false will yield 0.

share|improve this answer
The + is not "the" unary operator, it's one example of a unary operator. It's called "unary" because it takes one argument. Even the page you linked references another unary operator (-). You can compare with ternary operators—which take three arguments (e.g. foo ? bar : bat)—and many binary operators (e.g. foo + bar). The bang (!) is also a common unary operator. –  eyelidlessness Mar 7 '12 at 15:47

For the record: Number will also convert to 1 or 0:

sendMessage(this.name, Number(!event.target.checked), Number(event.target.checked));
share|improve this answer

Ah I forgot that rep doesn't transfer over, apparently I don't have enough to comment. I was going to reply to Cygal's comment on Raynos's answer:

While it is true that +true == 1, and +false == 0 that isn't exactly helpful since true == 1 and false == 0 as well. You probably meant to say that +true === 1 and +false === 0

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.