Have you seen this?

(N ^= 1)

I was a bit stumped by this, I have not seen this before in JavaScript. Chances are you may not have seen it before either.

I wrote a quick little JSFiddle to try and see what it does. But before I get into that I thought I should get into where I found it.

I wanted to find a way to validate a credit card. To know roughly if it is valid before leaving a form. I stumbled across something called, “The Luhn Formula.”

This Luhn formula sparked my interest so I started reading about it, here, and found it interesting. I was looking at some solutions that others have come up with and found an interesting one, here

On line 16, I found: (bit ^= 1)and instantly started searching to figure out what it is. I couldn’t find an answer though so I wrote a fiddle that can be found at https://jsfiddle.net/Antmanx2/cfn3zhsm/.

I got the following results:

  • A= 0 Value= 1
  • A= 1 Value= 0
  • A= 2 Value= 3
  • A= 3 Value= 2
  • A= 4 Value= 5
  • A= 5 Value= 4
  • A= 6 Value= 7
  • A= 7 Value= 6
  • A= 8 Value= 9
  • A= 9 Value= 8
  • A= 10 Value= 11

After looking at the results I found the pattern, when Even it adds one to N and when odd it subtracts one from N. 

I figured it out, it is a Bit Operator, XOR. Not something I have used a huge amount and have never seen it in JavaScript so I thought I would share. Hope you find this helpful!

Leave a Reply