# How to transform true and false to 1 and 0?

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?

-

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 ಠ_ಠ)

-
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.

-
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

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

-

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

sendMessage(this.name, Number(!event.target.checked), Number(event.target.checked));

-