3
\$\begingroup\$

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?

\$\endgroup\$

4 Answers 4

8
\$\begingroup\$

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

\$\endgroup\$
2
  • 2
    \$\begingroup\$ LA_, note that +true == 1, and +false == 0 in JS. \$\endgroup\$ Mar 3, 2012 at 20:47
  • \$\begingroup\$ The real answer is in the comments \$\endgroup\$
    – pbarney
    Aug 23, 2017 at 16:19
6
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Mar 7, 2012 at 15:47
3
\$\begingroup\$

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

sendMessage(this.name, Number(!event.target.checked), Number(event.target.checked));
\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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